免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1850 | 回复: 0
打印 上一主题 下一主题

Python的线程池实现 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2009-08-21 15:35 |只看该作者 |倒序浏览

实现代码:
#coding:utf-8
import Queue
import threading
import sys
import time
import urllib
#替我们工作的线程池中的线程
class MyThread(threading.Thread):
def __init__(self, workQueue, resultQueue,timeout=30, **kwargs):
  threading.Thread.__init__(self, kwargs=kwargs)
  #线程在结束前等待任务队列多长时间
  self.timeout = timeout
  self.setDaemon(True)
  self.workQueue = workQueue
  self.resultQueue = resultQueue
  self.start()
def run(self):
  while True:
   try:
    #从工作队列中获取一个任务
    callable, args, kwargs = self.workQueue.get(timeout=self.timeout)
    #我们要执行的任务
    res = callable(args, kwargs)
    #报任务返回的结果放在结果队列中
    self.resultQueue.put(res+" | "+self.getName())   
   except Queue.Empty: #任务队列空的时候结束此线程
    break
   except :
    print sys.exc_info()
    raise
   
class ThreadPool:
def __init__( self, num_of_threads=10):
  self.workQueue = Queue.Queue()
  self.resultQueue = Queue.Queue()
  self.threads = []
  self.__createThreadPool( num_of_threads )
def __createThreadPool( self, num_of_threads ):
  for i in range( num_of_threads ):
   thread = MyThread( self.workQueue, self.resultQueue )
   self.threads.append(thread)
def wait_for_complete(self):
  #等待所有线程完成。
  while len(self.threads):
   thread = self.threads.pop()
   #等待线程结束
   if thread.isAlive():#判断线程是否还存活来决定是否调用join
    thread.join()
   
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.urlopen('http://www.google.com/')
  html = conn.read(20)
except:
  print  sys.exc_info()
return  html
def test():
print 'start testing'
tp = 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 length == %d '% tp.resultQueue.qsize()
while tp.resultQueue.qsize():
  print tp.resultQueue.get()
print 'end testing'
if __name__ == '__main__':
test()
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/84280/showart_2033764.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP