python实现线程池通常使用threading或thread模块来编写,现在已经有了threadpool模块来实现线程池。
英文文档见:http://www.chrisarndt.de/projects/threadpool/
中文文档见:http://gashero.yeax.com/?p=44
现给出一个简易的使用threadpool模块来实现线程池的例子:
import threadpool
import time,random
def hello(str):
time.sleep(2)
return str
def print_result(request, result):
print "the result is %s %r" % (request.requestID, result)
data = [random.randint(1,10) for i in range(20)]
pool = threadpool.ThreadPool(5)
requests = threadpool.makeRequests(hello, data, print_result)
[pool.putRequest(req) for req in requests]
pool.wait()