Python的线程池实现_第1页
Python的线程池实现_第2页
Python的线程池实现_第3页
Python的线程池实现_第4页
全文预览已结束

付费下载

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、1234567891011121314151617181920212223242526272829303132333435363738394041Pytho n的线程池实现代码#codin g:utf-8#Python的线程池实现import Queueimport threadi ngimport sysimport timeimport urllib#替我们工作的线程池中的线程class MyThread(threading.Thread):def _init_ (self, workQueue, resultQueue,timeout=30, *kwargs):threadi ng.Th

2、read._init_ (self, kwargs=kwargs)#线程在结束前等待任务队列多长时间self.timeout = timeoutself.setDaem on( True)self.workQueue = workQueueself.resultQueue = resultQueueself.start()def run( self):while True:try :#从工作队列中获取一个任务callable, args, kwargs = self.workQueue.get(timeout=self.timeout)#我们要执行的任务res = callable(args,

3、 kwargs)#报任务返回的结果放在结果队列中self.resultQueue.put(res+ | +self.getName()except Queue.Empty:#任务队列空的时候结束此线程breakexcept :print sys.exc_info()raiseclass ThreadPool:def _init_( self, num_of_threads=10):self.workQueue = Queue.Queue()self.resultQueue = Queue.Queue() self.threads =4243444546474849505152535455565

4、75859606162636465666768697071727374757677787980818283def _createThreadPool( self, num_of_threads ):for i in range( num_of_threads ):thread = MyThread( self.workQueue, self.resultQueue ) self.threads.appe nd(thread)def wait_for_complete(self):#等待所有线程完成。while len(self.threads):thread = self.threads.po

5、p()#等待线程结束if thread.isAlive():#判断线程是否还存活来决定是否调用jointhread.joi n()def add_job( self, callable, *args, *kwargs ):self.workQueue.put( (callable,args,kwargs)def test_job(id, sleep = 0.001 ):html =try :time.sleep(1)conn = urllib.urlope n(/)html = conn. read(20)except :print sys.exc_ info()return htmldef test():print start testi ngtp = ThreadPool(10)for i in range(50):time.sleep(0.2)tp.add_job( test_job, i, i*0.001 )tp.wait_for_complete()#处理结果print result Queue s len gth = %d % tp.resultQueue.qsize() while

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论