python用Queue多线程干活的脚本
#!/usr/bin/env python import Queue import threading import time import random q=Queue.Queue(0) NUM_WORKERS = 3 class MyThread(threading.Thread): """A worker thread.""" def __init__(self, input, worktype): self._jobq = input self._work_type = worktype threading.Thread.__init__(self) def run(self): """ Get a job and process it. Stop when there's no more jobs """ while True: if self._jobq.qsize()>0: job = self._jobq.get() worktype=self._work_type self._process_job(job,worktype) else: break def _process_job(self, job,worktype): """ Do useful work here. worktype: let this thread do different work 1,do list 2,do item 3,,, """ doJob(job) def doJob(job): """ do work function 1 """ time.sleep(random.random()*3) print "doing ",job if __name__=='__main__': print "begin..." #put some work to q for i in range(NUM_WORKERS*2): q.put(i) #print total job q's size print "job q'size",q.qsize() #start threads to work for x in range(NUM_WORKERS): MyThread(q,x).start() #if q is not empty, wait #while q.qsize()>0: # time.sleep(0.1)
《 “改写地一个python利用Queue多线程干活的脚本” 》 有 7 条评论
写得真TMD乱七八糟! 没那本事, 别tmd乱放在博客里误导那些新人.
self._process_job(job,worktype) worktype, 哪儿来的? 没检查都好意思写博文?
利用queue与list的效率有何区别
不同的数据类型,可能要看具体应用吧。没有做过测试,queue做集合操作的时候,速度我比较满意。
谢谢上海探戈的改正,另外,对于多线程有没有比较好的概念介绍?
只是代码的话看得还是乱七八糟的。
你要啥概念?进程和线程的区别?
22行,“> ;” ==== > “>”
最近也在学习python 的多线程。百度搜索关键字 “python 多线程“ 找到你。谢谢提供