【问题标题】:Python Concurrency: Wait for one out of few futures and cancel the restPython并发:等待少数期货之一并取消其余期货
【发布时间】:2018-02-05 19:03:48
【问题描述】:

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

就执行时间而言,有一个函数非常冗长且不确定(它获取代理、发送 HTTP 请求等)。

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

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

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

我尝试在 SO 中的几个地方查看,例如 python concurrency question,但仍然无法理解如何精确地做到这一点。

【问题讨论】:

    标签: python python-3.x concurrency


    【解决方案1】:

    您可以将 concurrent.futures.wait 与 return_when=FIRST_COMPLETED 选项一起使用(它将等待多个期货,但在其中任何一个完成后立即返回)。但更简单的是使用 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
    

    【讨论】:

      猜你喜欢
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 2014-02-04
      • 2013-04-27
      • 1970-01-01
      • 2015-06-03
      相关资源
      最近更新 更多