我有以下代码,已经简化:
import concurrent.futures
pool = concurrent.futures.ThreadPoolExecutor(8)
def _exec(x):
return x + x
myfuturelist = pool.map(_exec,[x for x in range(5)])
# How do I wait for my futures to finish?
for result in myfuturelist:
# Is this how it's done?
print(result)
#... stuff that should happen only after myfuturelist is
#completely resolved.
# Documentation says pool.map is asynchronous
关于ThreadPoolExecutor.map的文档很薄弱。帮助会很棒。
谢谢!
答案 0 :(得分:2)
Executor.map 将并行运行作业并等待期货完成,收集结果并返回生成器。它已经等你了。如果设置超时,它将等到超时并在生成器中抛出异常。
map(func,* iterables,timeout = None,chunksize = 1)
- 立即收集迭代物而不是懒惰;
- func以异步方式执行,并且可以同时对func进行多次调用。
要获取期货清单并手动进行等待,您可以使用:
myfuturelist = [pool.submit(_exec, x) for x in range(5)]
Executor.submit 会返回future个对象,将来会调用result
明确等待它完成:
myfutrelist[0].result() # wait the 1st future to finish and return the result
答案 1 :(得分:0)
在所有任务完成之前,对ThreadPoolExecutor.map
的调用不会被阻塞。使用wait执行此操作。
from concurrent.futures import wait, ALL_COMPLETED
...
futures = [pool.submit(fn, args) for args in arg_list]
wait(futures, timeout=whatever, return_when=ALL_COMPLETED) # ALL_COMPLETED is actually the default
do_other_stuff()
您还可以在list(results)
返回的生成器上调用pool.map
来强制求值(这是您在原始示例中所做的事情)。但是,如果您实际上并没有使用任务返回的值,那么wait
是您的理想选择。