ThreadPoolExecutor with context manager

本小妞迷上赌 提交于 2019-12-10 20:26:16

问题


I don't understand why this code is behaving in different way. In the first case, the code will print 'elo' and after 19 seconds we will see '3'.

In other case we will be first wait 19 seconds, and after that we will see 'elo'.

Could you explain me that?

from concurrent.futures import ThreadPoolExecutor

def wait_on_future():
    f = 3
    import time
    time.sleep(19)
    print(f)

executor = ThreadPoolExecutor(max_workers=2)
executor.submit(wait_on_future)
print("elo")

vs

from concurrent.futures import ThreadPoolExecutor

def wait_on_future():
    f = 3
    import time
    time.sleep(19)
    print(f)

with ThreadPoolExecutor(max_workers=2) as executor:      
    executor.submit(wait_on_future)
print("elo")

回答1:


Your first program does not explicitly close the pool. You submit your task with executor.submit(), which is a non-blocking call. Your main program processes to print statement immediately and just hangs there until all threads have finished after 19 seconds.

Your second program uses with statement, which in this context is blocking. with ThreadPoolExecutor() has an implicit shutdown(wait=True), and it blocks there until all threads have completed processing. See https://docs.python.org/3/library/concurrent.futures.html

This makes your program1 identical in functionality as is your program 2:

executor = ThreadPoolExecutor(max_workers=2)
executor.submit(wait_on_future)
executor.shutdown(wait=True)
print("elo")

Hope this helps.



来源:https://stackoverflow.com/questions/48704976/threadpoolexecutor-with-context-manager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!