python 多线程优先队列Queue,pythonqueue,Queue模块允许创建指


Queue模块允许创建指定长度的队列.下面是Queue模块的常用方法:

get():删除并返回队列中的一个项目

put():添加项目到队列

qsize():返回队列中元素的个数empty():队列为空返回True否则返回False

full():队列已满返回True,负责返回False```python

!/usr/bin/python

import Queueimport threadingimport time

exitFlag = 0

class myThread (threading.Thread): def init(self, threadID, name, q): threading.Thread.init(self) self.threadID = threadID self.name = name self.q = q def run(self): print "Starting " + self.name process_data(self.name, self.q) print "Exiting " + 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

Create new threads

for tName in threadList: thread = myThread(threadID, tName, workQueue) thread.start() threads.append(thread) threadID += 1

Fill the queue

queueLock.acquire()for word in nameList: workQueue.put(word)queueLock.release()

Wait for queue to empty

while not workQueue.empty(): pass

Notify threads it's time to exit

exitFlag = 1

Wait for all threads to complete

for t in threads: t.join()print "Exiting Main Thread"

输出结果如下:```pythonStarting Thread-1Starting Thread-2Starting Thread-3Thread-1 processing OneThread-2 processing TwoThread-3 processing ThreeThread-1 processing FourThread-2 processing FiveExiting Thread-3Exiting Thread-1Exiting Thread-2Exiting Main Thread

评论关闭