我如何等待 ThreadPoolExecutor.map 完成

新手上路,请多包涵

我有以下代码,已简化:

 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 的文档薄弱。帮助会很棒。

谢谢!

原文由 Dr.Knowitall 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.1k
2 个回答

Executor.map 将并行运行作业并等待 futures 完成,收集结果并返回生成器。它已经完成了对你的等待。如果设置超时,它将等到超时并在生成器中抛出异常。

地图(功能,*迭代器,超时=无,块大小=1)

  • 立即而不是懒惰地收集可迭代对象;
  • func 是异步执行的,并且可以同时对 func 进行多次调用。

要获取期货列表并手动等待,您可以使用:

 myfuturelist = [pool.submit(_exec, x) for x in range(5)]

Executor.submit 将返回一个 未来 的对象,调用 result 未来将明确等待它完成:

 myfutrelist[0].result() # wait the 1st future to finish and return the result

原文由 CtheSky 发布,翻译遵循 CC BY-SA 3.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 是可行的方法。

原文由 mway 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题