gpt4 book ai didi

Python 并发 : Wait for one out of few futures and cancel the rest

转载 作者:太空宇宙 更新时间:2023-11-04 04:49:42 24 4
gpt4 key购买 nike

我通常使用 concurrent.futures.ThreadPoolExecutor 在 python 中并发执行任务。

有一个函数在执行所需的时间方面非常冗长且不确定(它获取代理、发送 HTTP 请求等)。

我想调用它几次(比方说 2 次),这对我来说变得复杂了:

一个任务完成时,我想检查它的返回值,如果它是真的,继续代码路径,我不再关心第二个任务,那里无需再等待了。

但如果返回值为 False,我想等待第二个任务完成,然后继续执行代码路径。

我试着在 SO 的几个地方查看,像这样 python concurrency question但仍然无法理解如何准确地做到这一点。

最佳答案

您可以将 concurrent.futures.wait 与 return_when=FIRST_COMPLETED 选项一起使用(它将等待多个 future ,但一旦其中任何一个完成就返回)。但更简单的方法是使用 concurrent.futures.as_completed,它为您提供了一个迭代器,可在未来完成或取消时返回它们。

f1 = executor.submit(job_1)
f2 = executor.submit(job_2)
for f in concurrent.futures.as_completed((f1,f2)):
if f.completed() and f.result():
# a job completed and returned True, so skip the rest
break
else:
# handle case where none of the tasks succeeded
pass
# normal code path

关于Python 并发 : Wait for one out of few futures and cancel the rest,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48629688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com