为什么 concurrent.futures' submit() 不立即 returns 控制到主程序?

Why doesn't concurrent.futures' submit() immediately returns control to the main program?

我正在学习 concurrent.futures(从 threading 开始),但我不明白提交和等待的具体工作原理。

考虑以下代码,有两个线程启动,其中一个应该立即结束,而另一个无限期挂起。

我的期望是两个线程都将通过 submit() 启动,并且控制权会立即交还给主程序。

在那之后 wait() 超时将 return 一个 donenot_done 线程的元组(not_done 一个将被强制中断到超时为止)。

import concurrent.futures
import time

def worker(wait_infinite):
    if wait_infinite:
        time.sleep(100)

with concurrent.futures.ThreadPoolExecutor() as executor:
    inf = executor.submit(worker, True)
    not_inf = executor.submit(worker, False)

res = concurrent.futures.wait([inf, not_inf], timeout=2)
print(res)

发生的情况是执行在 not_inf = executor.submit(worker, False) 上挂起。 为什么不把控制权交还给主程序?

在 with 语句执行器的末尾调用 executor.shutdown。等待所有线程完成。您应该将 wait 移动到 with 语句中, 然后调用 executor.shutdown(False) 停止等待挂起的线程。(编辑:您无法正确取消 运行 thread 除非合作或者如果它在不同的进程中 )

source

executor.shutdown(wait=True)

Signal the executor that it should free any resources that it is using when the >currently pending futures are done executing. Calls to Executor.submit() and >Executor.map() made after shutdown will raise RuntimeError.

If wait is True then this method will not return until all the pending futures are done executing and the resources associated with the executor have been freed. If wait is False then this method will return immediately and the resources associated with the executor will be freed when all pending futures are done executing. Regardless of the value of wait, the entire Python program will not exit until all pending futures are done executing.

You can avoid having to call this method explicitly if you use the with statement, which will shutdown the Executor (waiting as if Executor.shutdown() were called with wait set to True):