Python的线程池实现

实现代码:

#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()

 

参考资料:http://blog.daviesliu.net/2006/10/09/234822/

http://hi.baidu.com/flowsing/blog/item/76cccbfbe1b76e214f4aeab8.html

http://www.ibm.com/developerworks/cn/aix/library/au-threadingpython/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值