import os
from concurrent.futures import ThreadPoolExecutor,as_completed
def func(arg):
return arg
# 五任务三线程示例
arg = " "
# submit用法,命名各个任务,用result()获得其返回值
with ThreadPoolExecutor(max_workers=3) as executor:
t_list = []
for i in range(5):
t = executor.submit(func, arg)
t_list.append(t)
# t_list = [executor.submit(func, arg) for i in range(5)] #推导式
# as_completed() 方法是一个生成器,在没有任务完成的时候,会一直阻塞,除非设置了 timeout,一旦有一个任务完成,就会返回结果,其他没有完成的任务继续阻塞。
for t in as_completed(t_list):
t.result() #返回值
# map用法,map函数生成一个迭代器,用for循环获取值
with ThreadPoolExecutor(max_workers=6) as executor:
results = executor.map(func, [arg, arg, arg, arg, arg])
for result in results:
print(result)
python线程池范例ThreadPoolExecutor
于 2024-03-01 20:06:42 首次发布