協程中呼叫阻塞函式
阿新 • • 發佈:2018-11-14
from concurrent.futures import ThreadPoolExecutor from tornado import gen threadpool = ThreadPoolExecutor(2) def mySleep(count): import time for i in range(count): print(i) time.sleep(1) @gen.coroutine def call_block(): print("start") threadpool.submit(mySleep,5) #阻塞函式不會影響協程執行 # mySleep(10) #阻塞函式阻塞協程執行,阻塞函式執行完成才能繼續執行協程 # yield threadpool.submit(mySleep,5) #阻塞函式阻塞協程執行,函式執行完返回,協程不在繼續執行! # yield mySleep(5) #end未列印 print('end') call_block()
from concurrent.futures import ThreadPoolExecutor:匯入執行緒池庫
例項化了一個有兩個執行緒的執行緒池,協程中使用threadpool.submit呼叫阻塞函式,通過yield返回,這樣不會阻塞協程的繼續執行,也保證阻塞函式順序執行!