Reputation: 3979
I'm new to python and just trying a simple threading example. But I can't explain myself why this code is working synchronous:
from concurrent.futures import ThreadPoolExecutor
import time
def return_after_3_secs():
time.sleep(3)
return
def callback_method(future):
print ("Hello World.")
with ThreadPoolExecutor(2) as pool:
future = pool.submit(return_after_3_secs)
future.add_done_callback(callback_method)
print ("1")
time.sleep(1)
print ("2")
time.sleep(1)
print ("3")
print (future.result())
I'm basically from C# and thinking of a future as a Task
in C#. So this is a handle or token for the new Thread.
I would expect following output:
- 1
- 2
- 3
- Hello World.
- None
But I'm getting:
- Hello World.
- 1
- 2
- 3
- None
Before something is printed the Console wait for 3 seconds. So this code is running synchron. Can someone help me up with the understanding of futures and tell me why the time.sleep(3)
isn't running on second thread?
Upvotes: 2
Views: 666
Reputation: 368944
The statements after the with ThreadPoolExecutor(..)
is executed after the statements inside the with ..
statements done.
(because with ThreadPoolExecutor(..)
internally calls executor.shutdown(wait=True)
to wait the pending futures done, and related resources freed. See concurrent.futures.Executor.shutdown
)
By indenting those statement (print
, time.sleep
) inside the with
statement, you will get what you want.
with ThreadPoolExecutor(2) as pool:
future = pool.submit(return_after_3_secs)
future.add_done_callback(callback_method)
print ("1")
time.sleep(1)
print ("2")
time.sleep(1)
print ("3")
Upvotes: 4