[英]function of `with` in `concurrent.futures`
下面的代碼通過返回幾乎為零的總完成時間按預期執行,因為它不等待線程完成每個作業。
import concurrent.futures
import time
start = time.perf_counter()
def do_something(seconds):
print(f'Sleeping {seconds} second(s)...')
time.sleep(seconds)
return f'Done Sleeping...{seconds}'
executor= concurrent.futures.ThreadPoolExecutor()
secs = [10, 4, 3, 2, 1]
fs = [executor.submit(do_something, sec) for sec in secs]
finish = time.perf_counter()
print(f'Finished in {round(finish-start, 2)} second(s)')
但是使用with
命令它會等待:
with concurrent.futures.ThreadPoolExecutor() as executor:
secs = [10, 4, 3, 2, 1]
fs = [executor.submit(do_something, sec) for sec in secs]
為什么? 多線程with
這種行為的原因是什么?
在with
語句中使用concurrent.futures.Executor
相當於在使用后調用Executor.shutdown
—— 導致 executor 等待所有任務完成。 with
中使用的Executor
可以保證正確關閉並發任務,即使在with
塊內發生錯誤也是如此。
Executor.shutdown ( wait=True )
當當前掛起的期貨完成執行時,向執行器發出信號,它應該釋放它正在使用的任何資源。 關機后調用
Executor.submit()
和Executor.map()
將引發RuntimeError
。[...]
如果您使用
with
語句,您可以避免顯式調用此方法,該語句將關閉Executor
(等待就好像Executor.shutdown()
被調用且wait設置為True
):[...]
concurrent.futures
沒有很好的文檔記錄。 創建執行程序時,必須關閉它才能終止其線程或進程。 該代碼將通過向線程推送None
命令來指示線程退出,然后等待它們完成。 在您的第一種情況下,如果您添加了executor.shutdown()
您會看到延遲。 無論如何它就在那里 - 程序仍然需要 10 秒才能退出。
執行器可以用作上下文管理器(它作為__enter__
和__exit__
方法)。 當它退出“with”塊時,會調用__exit__
,然后它會為您執行shutdown
調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.