Python3 并发未来似乎无法异步工作

Python3 concurrent future doesn't seem to work async

我是 python 的新手,只是想尝试一个简单的线程示例。但我自己无法解释为什么这段代码是同步工作的:

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

我基本上来自 C#,并且认为未来是 C# 中的 Task。所以这是新线程的句柄或标记。

我希望得到以下输出:

  1. 1
  2. 2
  3. 3
  4. Hello World.
  5. None

但我得到:

  1. Hello World.
  2. 1
  3. 2
  4. 3
  5. None

在打印内容之前,控制台等待 3 秒。所以这段代码是 运行 同步的。有人可以帮助我了解期货并告诉我为什么 time.sleep(3) 在第二个线程上不是 运行 吗?

with ThreadPoolExecutor(..)之后的语句在with ..语句完成后执行。

(因为 with ThreadPoolExecutor(..) 内部调用 executor.shutdown(wait=True) 等待未完成的期货完成,相关资源已释放。参见 concurrent.futures.Executor.shutdown

通过在 with 语句中缩进那些语句(printtime.sleep),您将得到想要的结果。

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