python 线程池

一个老外的开源项目中用的线程池代码,总共有 task, workthread, threadpool三大部分。不太清楚的是你说的queue是什么lib?

Python代码 复制代码  收藏代码
  1. import threading   
  2.   
  3. class WorkerTask(object):   
  4.     """A task to be performed by the ThreadPool."""  
  5.   
  6.     def __init__(self, function, args=(), kwargs={}):   
  7.         self.function = function   
  8.         self.args = args   
  9.         self.kwargs = kwargs   
  10.   
  11.     def __call__(self):   
  12.         self.function(*self.args, **self.kwargs)   
  13.   
  14.   
  15. class WorkerThread(threading.Thread):   
  16.     """A thread managed by a thread pool."""  
  17.   
  18.     def __init__(self, pool):   
  19.         threading.Thread.__init__(self)   
  20.         self.setDaemon(True)   
  21.         self.pool = pool   
  22.         self.busy = False  
  23.         self._started = False  
  24.         self._event = None  
  25.   
  26.     def work(self):   
  27.         if self._started is True:   
  28.             if self._event is not None and not self._event.isSet():   
  29.                 self._event.set()   
  30.         else:   
  31.             self._started = True  
  32.             self.start()   
  33.   
  34.     def run(self):   
  35.         while True:   
  36.             self.busy = True  
  37.             while len(self.pool._tasks) > 0:   
  38.                 try:   
  39.                     task = self.pool._tasks.pop()   
  40.                     task()   
  41.                 except IndexError:   
  42.                     # Just in case another thread grabbed the task 1st.   
  43.                     pass  
  44.   
  45.             # Sleep until needed again   
  46.             self.busy = False  
  47.             if self._event is None:   
  48.                 self._event = threading.Event()   
  49.             else:   
  50.                 self._event.clear()   
  51.             self._event.wait()   
  52.   
  53. class ThreadPool(object):   
  54.     """Executes queued tasks in the background."""  
  55.   
  56.     def __init__(self, max_pool_size=10):   
  57.         self.max_pool_size = max_pool_size   
  58.         self._threads = []   
  59.         self._tasks = []    
  60.   
  61.     def _addTask(self, task):   
  62.         self._tasks.append(task)   
  63.   
  64.         worker_thread = None  
  65.         for thread in self._threads:   
  66.             if thread.busy is False:   
  67.                 worker_thread = thread   
  68.                 break  
  69.   
  70.         if worker_thread is None and len(self._threads) <= self.max_pool_size:   
  71.             worker_thread = WorkerThread(self)   
  72.             self._threads.append(worker_thread)   
  73.   
  74.         if worker_thread is not None:   
  75.             worker_thread.work()   
  76.   
  77.     def addTask(self, function, args=(), kwargs={}):   
  78.         self._addTask(WorkerTask(function, args, kwargs))   
  79.   
  80. class GlobalThreadPool(object):   
  81.     """ThreadPool Singleton class."""  
  82.   
  83.     _instance = None  
  84.   
  85.     def __init__(self):   
  86.         """Create singleton instance """  
  87.   
  88.         if GlobalThreadPool._instance is None:   
  89.             # Create and remember instance   
  90.             GlobalThreadPool._instance = ThreadPool()   
  91.   
  92.     def __getattr__(self, attr):   
  93.         """ Delegate get access to implementation """  
  94.         return getattr(self._instance, attr)   
  95.   
  96.     def __setattr__(self, attr, val):   
  97.         """ Delegate set access to implementation """  
  98.         return setattr(self._instance, attr, val)  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值