Skip to main content
 首页 » 编程设计

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

2025年01月19日10傻小

我通常使用 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