【问题标题】:How to stop all threads if there is an exception in one thread?如果一个线程出现异常,如何停止所有线程?
【发布时间】:2022-07-19 00:21:03
【问题描述】:

我目前正在使用 python 的 concurrent.futures 库运行一个函数。它看起来像这样(我使用的是 Python 3.10.1):

    with concurrent.futures.ThreadPoolExecutor() as executor:

    future_results = [executor.submit(f.get_pdf_multi_thread, ssn) for ssn in ssns]

    for future in concurrent.futures.as_completed(future_results):
        try:
            future.result()
        except Exception as exc:
            # If there is one exception in a thread stop all threads
            for future in future_results:
                future.cancel()
            raise exc

这样做的目的是,如果其中一个线程出现异常,则停止其余线程并抛出异常。但是我不知道这是否正在做它应该做的事情(有时需要很长时间才能抛出我想要的异常,而有时它会很快抛出它)。你能帮我解决这个问题吗?谢谢

【问题讨论】:

  • sys.exit 呢?
  • 只需使用executor.map()
  • 也许你可以用Coroutine代替多线程。
  • 如何设置 variablue run 为 true 或 false?
  • 说真的,list(executor.map(f.get_pdf_multi_thread, ssns)) 如果出现异常,将关闭所有线程。

标签: python python-3.x concurrent.futures


【解决方案1】:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    • 2016-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多