python ThreadPoolExecutor 线程池 使用例子

直接上代码

 

from queue import Queue
from concurrent.futures import ThreadPoolExecutor
def test(a):
    time.sleep(1)
    print("a",a)
    return {'a':a}
t=time.time()
q=Queue()
pool=ThreadPoolExecutor(max_workers=100)
lis=[x for x in range(200)]
[q.put(pool.submit(test,x)) for x in lis]
print('队列长度 ',q.qsize())
print('开始返回结果')
while 1:
    if q.qsize()==0:
        break
    pol=q.get()
    if pol.done():
        print('获取线程结果 ',pol.result())
    else:
        q.put(pol)
print('取完了 ',time.time()-t)
搜索