百度服务器建设自己的网站,广州天河网站制作,网站开发设计文档,哔哩哔哩网站电子商务建设导读Python 的 Queue 模块中提供了同步的、线程安全的队列类#xff0c;包括FIFO(先入先出)队列Queue#xff0c;LIFO(后入先出)队列LifoQueue#xff0c;和优先级队列 PriorityQueue。这些队列都实现了锁原语#xff0c;能够在多线程中直接使用#xff0c;可以使用队列来…导读Python 的 Queue 模块中提供了同步的、线程安全的队列类包括FIFO(先入先出)队列QueueLIFO(后入先出)队列LifoQueue和优先级队列 PriorityQueue。这些队列都实现了锁原语能够在多线程中直接使用可以使用队列来实现线程间的同步。Queue 模块中的常用方法:Queue.qsize() 返回队列的大小Queue.empty() 如果队列为空返回True,反之FalseQueue.full() 如果队列满了返回True,反之FalseQueue.full 与 maxsize 大小对应Queue.get([block[, timeout]])获取队列timeout等待时间Queue.get_nowait() 相当Queue.get(False)Queue.put(item) 写入队列timeout等待时间Queue.put_nowait(item) 相当Queue.put(item, False)Queue.task_done() 在完成一项工作之后Queue.task_done()函数向任务已经完成的队列发送一个信号Queue.join() 实际上意味着等到队列为空再执行别的操作实例:#!/usr/bin/python3import queueimport threadingimport timeexitFlag 0class myThread (threading.Thread):def __init__(self, threadID, name, q):threading.Thread.__init__(self)self.threadID threadIDself.name nameself.q qdef run(self):print (开启线程 self.name)process_data(self.name, self.q)print (退出线程 self.name)def process_data(threadName, q):while not exitFlag:queueLock.acquire()if not workQueue.empty():data q.get()queueLock.release()print (%s processing %s % (threadName, data))else:queueLock.release()time.sleep(1)threadList [Thread-1, Thread-2, Thread-3]nameList [One, Two, Three, Four, Five]queueLock threading.Lock()workQueue queue.Queue(10)threads []threadID 1# 创建新线程for tName in threadList:thread myThread(threadID, tName, workQueue)thread.start()threads.append(thread)threadID 1# 填充队列queueLock.acquire()for word in nameList:workQueue.put(word)queueLock.release()# 等待队列清空while not workQueue.empty():pass# 通知线程是时候退出exitFlag 1# 等待所有线程完成for t in threads:t.join()print (退出主线程)以上程序执行结果开启线程Thread-1开启线程Thread-2开启线程Thread-3Thread-3 processing OneThread-1 processing TwoThread-2 processing ThreeThread-3 processing FourThread-1 processing Five退出线程Thread-3退出线程Thread-2退出线程Thread-1退出主线程