Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (50.2k points)

In the initial case, the code will display 'elo' and after 19 seconds we will see '3'.

In other cases, I have to wait for 19 seconds, and after that, we will see 'elo'.

I don't know why this is happening:

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 Answer

0 votes
by (107k points)
edited by

Please be informed that your first code does not explicitly close the pool in python. You have submitted your task with executor.submit(), which is a non-blocking request. Your main code processes to display the statements immediately and just hangs there until all threads have terminated after 19 seconds.

Your other program uses the statement, which in this context is blocking. with ThreadPoolExecutor() method has an implicit shutdown(wait=True), and it blocks there till all threads have finished the processing. 

executor = ThreadPoolExecutor(max_workers=2)

executor.submit(wait_on_future)

executor.shutdown(wait=True)

print("elo")

 The below python tutorial video will help you get a better understanding of Automate Your Coding with Python!

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...