python 多线程优先队列Queue,pythonqueue,Queue模块允许创建指
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
相关内容
- 同步重庆时时彩的数据到本地数据库,,#!/usr/bin/e
- C段IP筛选整理去重.PY,ip.py,"""C段IP筛选整理去
- python十进制转二进制,可指定位数,python十进制,pytho
- python模拟鼠标拖动操作,python模拟拖动,## _*_ codin
- 下载全国城市空气质量历史数据,全国城市历史数据
- Python 爬小说灵棺夜行,,import urlli
- 正则的简单用法,简单用法,import re #导
- osx下用python自动登录服务器(iterm2),pythoniterm2,None
- 都取oracle注释i,取oracle注释i,None
- 原 第三方Linux版网易云音乐 (遇到登陆错误,还请upda
评论关闭