是否有与Java';什么是固定线程池?
Python中是否有一个简单的ThreadPool库,它有pool.execute(function,args)方法,当池满时(直到其中一个线程变为空闲)应该阻止该方法 我曾尝试使用多处理包中的ThreadPool,但其pool.apply\u async()函数在池已满时不会阻塞。实际上,我根本不了解它的行为。这有一个基于a的实现来执行阻塞。使用是否有与Java';什么是固定线程池?,java,python,multithreading,threadpool,Java,Python,Multithreading,Threadpool,Python中是否有一个简单的ThreadPool库,它有pool.execute(function,args)方法,当池满时(直到其中一个线程变为空闲)应该阻止该方法 我曾尝试使用多处理包中的ThreadPool,但其pool.apply\u async()函数在池已满时不会阻塞。实际上,我根本不了解它的行为。这有一个基于a的实现来执行阻塞。使用add_task在将执行的位置执行 from multiprocessing.pool import ThreadPool ## {{{ http:
add_task
在将执行的位置执行
from multiprocessing.pool import ThreadPool
## {{{ http://code.activestate.com/recipes/577187/ (r9)
from Queue import Queue
from threading import Thread
class Worker(Thread):
"""Thread executing tasks from a given tasks queue"""
def __init__(self, tasks):
Thread.__init__(self)
self.tasks = tasks
self.daemon = True
self.start()
def run(self):
while True:
func, args, kargs = self.tasks.get()
try: func(*args, **kargs)
except Exception, e: print e
self.tasks.task_done()
class ThreadPool:
"""Pool of threads consuming tasks from a queue"""
def __init__(self, num_threads):
self.tasks = Queue(num_threads)
for _ in range(num_threads): Worker(self.tasks)
def add_task(self, func, *args, **kargs):
"""Add a task to the queue"""
self.tasks.put((func, args, kargs))
def wait_completion(self):
"""Wait for completion of all the tasks in the queue"""
self.tasks.join()
if __name__ == '__main__':
from random import randrange
delays = [randrange(1, 10) for i in range(100)]
from time import sleep
def wait_delay(d):
print 'sleeping for (%d)sec' % d
sleep(d)
# 1) Init a Thread pool with the desired number of threads
pool = ThreadPool(20)
for i, d in enumerate(delays):
# print the percentage of tasks placed in the queue
print '%.2f%c' % ((float(i)/float(len(delays)))*100.0,'%')
# 2) Add the task to the queue
pool.add_task(wait_delay, d)
# 3) Wait for completion
pool.wait_completion()
## end of http://code.activestate.com/recipes/577187/ }}}
我修改了@ckhan answer并添加了回调功能
#来自的自定义线程池实现http://code.activestate.com/recipes/577187/
#用法:
#def worker_方法(数据):
#''进行处理''
#返回数据
#
#def on_complete_回调(数据,isfailed):
#打印('在完整的%s'%1!'数据上)
#
#池=线程池(5)
#对于范围(1,10)内的数据
#pool.add_任务(worker_方法,on_complete_回调,数据)
#pool.wait_completion()
从队列导入队列
从线程导入线程
导入线程
类工作者(线程):
“”“从给定任务队列执行任务的线程”“”
定义初始化(自我、任务、线程id):
线程。\uuuu初始化\uuuuu(自)
self.tasks=任务
self.daemon=True
self.start()
self.thread\u id=线程\u id
def运行(自):
尽管如此:
func,callback,args,kargs=self.tasks.get()
尝试:
数据=函数(*args,**kargs)
回调(数据,False)
除例外情况外,e:
回调(e,True)
self.tasks.task_done()
类线程池:
“”“使用队列中的任务的线程池”“”
def uu init uu(self,num_线程):
self.tasks=队列(线程数)
对于范围内的i(num_线程):Worker(self.tasks,i)
def add_任务(self、func、callback、*args、**kargs):
“”“将任务添加到队列”“”
self.tasks.put((func、回调、args、kargs))
def等待_完成(自我):
“”“等待队列中所有任务的完成”“”
self.tasks.join()
ThreadPool不支持池已满时的阻塞行为。。。正如Ognhej在他的问题中提到的。。。