网络爬虫--多线程

多线程:

什么是多线程:

  1. 理解:默认情况下,一个程序只有一个进程和一个线程,代码是依次线性执行的。而多线程则可以并发执行,一次性多个人做多件事,自然比单线程更快。

如何创建一个基本的多线程:

使用threading模块下的Thread类即可创建一个线程。这个类有一个target参数,需要指定一个函数,那么以后这个线程执行的时候,就会执行这个函数的代码。示例代码如下:

import time
import threading

def reading():
    for x in range(3):
        print("%d正在读..."%x)
        time.sleep(1)

def writeing():
    for x in range(3):
        print("%d正在写..." % x)
        time.sleep(1)

def multi_thread():
    th1 = threading.Thread(target=coding)
    th2 = threading.Thread(target=drawing)

    th1.start()
    th2.start()

if __name__ == '__main__':
    multi_thread()

查看当前线程:

  1. threading.current_thread:在线程中执行这个函数,会返回当前线程的对象。
  2. threading.enumerate:获取整个程序中所有的线程。

继承自threading.Thread类:

  1. 我们自己写的类必须继承自threading.Thread类。
  2. 线程代码需要放在run方法中执行。
  3. 以后创建线程的时候,直接使用我们自己创建的类来创建线程就可以了。
  4. 为什么要使用类的方式创建线程呢?原因是因为类可以更加方便的管理我们的代码,可以让我们使用面向对象的方式进行编程。
class CodingThread(threading.Thread):
    def run(self) -> None:
        the_thread = threading.current_thread()
        for x in range(3):
            print(f'{the_thread.name}正在coing-----{x}')
            sleep(1)

class DrawingThread(threading.Thread):
    def run(self) -> None:
        the_thread = threading.current_thread()
        for x in range(3):
            print(f'{the_thread.name}正在drawing------{x}')


def mul_thread():
    th1 = CodingThread(name='xiaohong')
    th2 = DrawingThread(name='xiaoming')
    th1.start()
    th2.start()

if __name__ == '__main__':
    mul_thread()

全局变量共享的问题:

在多线程中,如果需要修改全局变量,那么需要在修改全局变量的地方使用锁锁起来,执行完成后再把锁释放掉。
使用锁的原则:

  1. 把尽量少的和不耗时的代码放到锁中执行。
  2. 代码执行完成后要记得释放锁。
    在Python中,可以使用threading.Lock来创建锁,lock.acquire()是上锁操作,lock.release()是释放锁的操作。

生产者和消费者模式:

生产者和消费者模式是多线程开发中经常见到的一种模式。生产者的线程专门用来生产一些数据,然后存放到一个中间的变量中。消费者再从这个中间的变量中取出数据进行消费。通过生产者和消费者模式,可以让代码达到高内聚低耦合的目标,程序分工更加明确,线程更加方便管理。

Lock版本的生产者和消费者模式:

import threading
import random
gMoney = 0
gLock = threading.Lock()
gTimes = 0

class Producer(threading.Thread):
    def run(self) -> None:
        global gMoney
        global gTimes
        while True:
            gLock.acquire()
            if gTimes >= 10:
                gLock.release()
                break
            money = random.randint(0, 100)
            gMoney += money
            gTimes += 1
            print("%s生产了%d"%(threading.current_thread().name,money))
            gLock.release()
            
class Consumer(threading.Thread):
    def run(self) -> None:
        global gMoney
        while True:
            gLock.acquire()
            money = random.randint(0,100)
            if gMoney >= money:
                gMoney -= money
                print("%s消费了%d"%(threading.current_thread().name,money))
            else:
                if gTimes >= 10:
                    gLock.release()
                    break
                print("%s想消费%d,但是余额只有%d"%(threading.current_thread().name,money,gMoney))
            gLock.release()

def main():
    for x in range(5):
        th = Producer(name="生产者%d号"%x)
        th.start()

    for x in range(5):
        th = Consumer(name="消费者%d号"%x)
        th.start()

if __name__ == '__main__':
    main()

Condition版本的生产者和消费者模式:

Lock版本的生产者与消费者模式可以正常的运行。但是存在一个不足,在消费者中,总是通过while True死循环并且上锁的方式去判断钱够不够。上锁是一个很耗费CPU资源的行为。因此这种方式不是最好的。还有一种更好的方式便是使用threading.Condition来实现。threading.Condition可以在没有数据的时候处于阻塞等待状态。一旦有合适的数据了,还可以使用notify相关的函数来通知其他处于等待状态的线程。这样就可以不用做一些无用的上锁和解锁的操作。可以提高程序的性能。首先对threading.Condition相关的函数做个介绍,threading.Condition类似threading.Lock,可以在修改全局数据的时候进行上锁,也可以在修改完毕后进行解锁。以下将一些常用的函数做个简单的介绍:

  1. acquire:上锁。
  2. release:解锁。
  3. wait:将当前线程处于等待状态,并且会释放锁。可以被其他线程使用notify和notify_all函数唤醒。被唤醒后会继续等待上锁,上锁后继续执行下面的代码。
  4. notify:通知某个正在等待的线程,默认是第1个等待的线程。
  5. notify_all:通知所有正在等待的线程。notify和notify_all不会释放锁。并且需要在release之前调用。

代码如下:

import threading
import random
import time
gMoney = 0
gCondition = threading.Condition()
gTimes = 0

class Producer(threading.Thread):
    def run(self) -> None:
        global gMoney
        global gTimes
        while True:
            gCondition.acquire()
            if gTimes >= 10:
                gCondition.release()
                break
            money = random.randint(0, 100)
            gMoney += money
            gTimes += 1
            print("%s生产了%d,剩余%d"%(threading.current_thread().name,money,gMoney))
            gCondition.notify_all()
            gCondition.release()
            time.sleep(1)

class Consumer(threading.Thread):
    def run(self) -> None:
        global gMoney
        while True:
            gCondition.acquire()
            money = random.randint(0,100)
            while gMoney < money:
                if gTimes >= 10:
                    print("%s想消费%d,但是余额只有%d了,并且生产者已经不再生产了!"%(threading.current_thread().name,money,gMoney))
                    gCondition.release()
                    return
                print("%s想消费%d,但是余额只有%d了,消费失败!"%(threading.current_thread().name,money,gMoney))
                gCondition.wait()
            gMoney -= money
            print("%s消费了%d,剩余%d"%(threading.current_thread().name,money,gMoney))
            gCondition.release()
            time.sleep(1)


def main():
    for x in range(5):
        th = Producer(name="生产者%d号"%x)
        th.start()

    for x in range(5):
        th = Consumer(name="消费者%d号"%x)
        th.start()

if __name__ == '__main__':
    main()

线程安全的队列Queue:

在线程中,访问一些全局变量,加锁是一个经常的过程。如果你是想把一些数据存储到某个队列中,那么Python内置了一个线程安全的模块叫做queue模块。Python中的queue模块中提供了同步的、线程安全的队列类,包括FIFO(先进先出)队列Queue,LIFO(后入先出)队列LifoQueue。这些队列都实现了锁原语(可以理解为原子操作,即要么不做,要么都做完),能够在多线程中直接使用。可以使用队列来实现线程间的同步。相关的函数如下:
初始化Queue(maxsize):创建一个先进先出的队列。

  1. qsize():返回队列的大小。
  2. empty():判断队列是否为空。
  3. full():判断队列是否满了。
  4. get():从队列中取最后一个数据。默认情况下是阻塞的,也就是说如果队列已经空了,那么再调用就会一直阻塞,直到有新的数据添加进来。也可以使用block=False,来关掉阻塞。如果关掉了阻塞,在队列为空的情况获取就会抛出异常。
  5. put():将一个数据放到队列中。跟get一样,在队列满了的时候也会一直阻塞,并且也可以通过block=False来关掉阻塞,同样也会抛出异常。

实战例子:

'''
多线程下载王者荣耀壁纸
'''
import requests
from urllib import parse
from urllib import request
import os
import threading
import queue

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36",
    "Referer": "https://pvp.qq.com/web201605/wallpaper.shtml"
}


class Producer(threading.Thread):
    def __init__(self,page_queue,image_queue,*args,**kwargs):
        super(Producer, self).__init__(*args,**kwargs)
        self.page_queue = page_queue
        self.image_queue = image_queue

    def run(self) -> None:
        while not self.page_queue.empty():
            page_url = self.page_queue.get()
            resp = requests.get(page_url, headers=headers)
            result = resp.json()
            datas = result['List']
            for data in datas:
                image_urls = extract_images(data)
                name = parse.unquote(data['sProdName']).replace("1:1", "").strip()
                dir_path = os.path.join("images1", name)
                # images1/猪八戒-年年有余
                if not os.path.exists(dir_path):
                    os.mkdir(dir_path)
                for index,image_url in enumerate(image_urls):
                    self.image_queue.put({"image_url":image_url,"image_path":os.path.join(dir_path,"%d.jpg"%(index+1))})



class Consumer(threading.Thread):
    def __init__(self,image_queue,*args,**kwargs):
        super(Consumer, self).__init__(*args,**kwargs)
        self.image_queue = image_queue

    def run(self) -> None:
        while True:
            try:
                image_obj = self.image_queue.get(timeout=10)
                image_url = image_obj.get("image_url")
                image_path = image_obj.get("image_path")
                try:
                    request.urlretrieve(image_url, image_path)
                    print(image_path + "下载完成!")
                except:
                    print(image_path+"下载失败!")
            except:
                break


def extract_images(data):
    image_urls = []
    for x in range(1,9):
        image_url = parse.unquote(data['sProdImgNo_%d'%x]).replace("200", "0")
        image_urls.append(image_url)
    return image_urls



def main():
    page_queue = queue.Queue(18)
    image_queue = queue.Queue(1000)
    for x in range(0,18):
        page_url = "https://apps.game.qq.com/cgi-bin/ams/module/ishow/V1.0/query/workList_inc.cgi?activityId=2735&sVerifyCode=ABCD&sDataType=JSON&iListNum=20&totalpage=0&page={page}&iOrder=0&iSortNumClose=1&iAMSActivityId=51991&_everyRead=true&iTypeId=2&iFlowId=267733&iActId=2735&iModuleId=2735&_=1554457680964".format(page=x)
        page_queue.put(page_url)

    for x in range(3):
        th = Producer(page_queue,image_queue,name="生产者%d号"%x)
        th.start()

    for x in range(5):
        th = Consumer(image_queue,name="消费者%d号"%x)
        th.start()

if __name__ == '__main__':
    main()

GIL:

什么是GIL:

提到多线程,必然会接触到GIL。Python自带的解释器是CPython。CPython解释器的多线程实际上是一个假的多线程(在多核CPU中,只能利用一核,不能利用多核)。同一时刻只有一个线程在执行,为了保证同一时刻只有一个线程在执行,在CPython解释器中有一个东西叫做GIL(Global Intepreter Lock),叫做全局解释器锁。这个解释器锁是有必要的。因为CPython解释器的内存管理不是线程安全的。当然除了CPython解释器,还有其他的解释器,有些解释器是没有GIL锁的,见下面:

  1. Jython:用Java实现的Python解释器。不存在GIL锁。更多详情请见:https://zh.wikipedia.org/wiki/Jython
  2. IronPython:用.net实现的Python解释器。不存在GIL锁。更多详情请见:https://zh.wikipedia.org/wiki/IronPython
  3. PyPy:用Python实现的Python解释器。存在GIL锁。更多详情请见:https://zh.wikipedia.org/wiki/PyPy
    GIL虽然是一个假的多线程。但是在处理一些IO操作(比如文件读写和网络请求)还是可以在很大程度上提高效率的。在IO操作上建议使用多线程提高效率。在一些CPU计算操作上不建议使用多线程,而建议使用多进程。

有了GIL,为什么还需要Lock:

GIL只是保证全局同一时刻只有一个线程在执行,但是他并不能保证执行代码的原子性。也就是说一个操作可能会被分成几个部分完成,这样就会导致数据有问题。所以需要使用Lock来保证操作的原子性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值