为什么 concurrent.futures.ThreadPoolExecutor().submit return 不立即?
Why doesn't concurrent.futures.ThreadPoolExecutor().submit return immediately?
在此代码中:
import concurrent.futures
import time
def pafter(t):
time.sleep(t)
print('Hi')
with concurrent.futures.ThreadPoolExecutor(5) as e:
e.submit(pafter, 2)
print('With returned')
我希望看到:
With returned
Hi
但我看到了:
Hi
With returned
为什么 submit
return 不立即?我要改变什么才能做到这一点?
使用with
语句相当于调用executor.shutdown()
,which is documented like this:
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)
粗体部分解释了您所看到的行为; submit()
调用立即执行 return,但 with
语句将阻塞,直到完成所有提交的工作。要更改它,您不需要使用 with
语句,而是显式调用 shutdown(wait=False)
.
在此代码中:
import concurrent.futures
import time
def pafter(t):
time.sleep(t)
print('Hi')
with concurrent.futures.ThreadPoolExecutor(5) as e:
e.submit(pafter, 2)
print('With returned')
我希望看到:
With returned
Hi
但我看到了:
Hi
With returned
为什么 submit
return 不立即?我要改变什么才能做到这一点?
使用with
语句相当于调用executor.shutdown()
,which is documented like this:
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)
粗体部分解释了您所看到的行为; submit()
调用立即执行 return,但 with
语句将阻塞,直到完成所有提交的工作。要更改它,您不需要使用 with
语句,而是显式调用 shutdown(wait=False)
.