Python3并发未来似乎并不工作异步

时间:2017-03-06 09:52:08

标签: python python-3.x python-multithreading

我是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.   
  3. 2
  4.   
  5. 3
  6.   
  7. Hello World。
  8.   
  9.   

但我得到了:

  
      
  1. Hello World。
  2.   
  3. 1
  4.   
  5. 2
  6.   
  7. 3
  8.   
  9.   

在打印某些内容之前,控制台会等待3秒钟。所以这段代码正在运行同步。有人可以帮助我理解未来,并告诉我time.sleep(3)为什么不在第二个线程上运行?

1 个答案:

答案 0 :(得分:4)

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

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

通过在print语句中缩进这些语句(time.sleepwith),您将得到您想要的内容。

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