Mariusz
Mariusz

Reputation: 369

ThreadPoolExecutor with context manager

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")

Upvotes: 10

Views: 6651

Answers (1)

Hannu
Hannu

Reputation: 12215

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.

Upvotes: 20

Related Questions