简体   繁体   中英

Python3 concurrent future doesn't seem to work async

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. 1
  2. 2
  3. 3
  4. Hello World.
  5. None

But I'm getting:

  1. Hello World.
  2. 1
  3. 2
  4. 3
  5. 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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM