当前位置: 代码迷 >> 综合 >> 【Python网络爬虫】150讲轻松搞定Python网络爬虫付费课程笔记 篇十九——多线程爬虫实战:Queue线程安全队列
  详细解决方案

【Python网络爬虫】150讲轻松搞定Python网络爬虫付费课程笔记 篇十九——多线程爬虫实战:Queue线程安全队列

热度:44   发布时间:2024-02-22 03:50:26.0

Queue 线程安全队列

python内置queue 模块,用于线程安全管理,它提供了同步的、线程安全的队列类,包括FIFO, LIFO队列。这些队列都实现了锁原语,能在多线程中直接使用。可以使用队列来实现线程间的同步。

相关函数如下:

  1. Queue(maxsize):创建一个先进先出的队列
  2. qsize():返回队列的大小
  3. empty():判断队列是否为空
  4. full():判断队列是否满
  5. get():获取队列最后一个数据
  6. put():将数据放入队列
from queue import Queueq = Queue(4)for x in range(5):try:q.put(x, block=False)#block=false表示非阻塞,当队列满了再添加时会抛出异常, 默认情况下为阻塞except:break
print(q.qsize())if q.full():print('满了')for x in range(5):try:value = q.get(block=False)except:breakprint(value)if q.empty():print("空")print('完成')

 

 

一个例子:

import random
import threading
import time
from queue import Queuedef add_value(q):while True:q.put(random.randint(0, 10))time.sleep(1)def get_value(q):while True:print('获得到值:%d'%q.get())def main():q = Queue(10)th1 = threading.Thread(target=add_value, args=[q])th2 = threading.Thread(target=get_value, args=[q])th1.start()th2.start()if __name__ == '__main__':main()

 

  相关解决方案