新聞中心
前面的代碼都是異步的,就如sleep,需要用asyncio.sleep而不是阻塞的time.sleep,如果有同步邏輯,怎么利用asyncio實現(xiàn)并發(fā)呢?答案是用run_in_executor。在一開始我說過開發(fā)者創(chuàng)建 Future 對象情況很少,主要是用run_in_executor,就是讓同步函數(shù)在一個執(zhí)行器( executor)里面運行。

成都創(chuàng)新互聯(lián)主要從事做網(wǎng)站、網(wǎng)站制作、網(wǎng)頁設計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務。立足成都服務將樂,十年網(wǎng)站建設經(jīng)驗,價格優(yōu)惠、服務專業(yè),歡迎來電咨詢建站服務:18982081108
同步代碼
def a():
time.sleep(1)
return 'A'
async def b():
await asyncio.sleep(1)
return 'B'
def show_perf(func):
print('*' * 20)
start = time.perf_counter()
asyncio.run(func())
print(f'{func.__name__} Cost: {time.perf_counter() - start}')
async def c1():
loop = asyncio.get_running_loop()
await asyncio.gather(
loop.run_in_executor(None, a),
b()
)
In : show_perf(c1)
********************
c1 Cost: 1.0027242230000866可以看到用run_into_executor可以把同步函數(shù)邏輯轉化成一個協(xié)程,且實現(xiàn)了并發(fā)。這里要注意細節(jié),就是函數(shù)a是普通函數(shù),不能寫成協(xié)程,下面的定義是錯誤的,不能實現(xiàn)并發(fā):
async def a(): time.sleep(1) return 'A'
因為 a 里面沒有異步代碼,就不要用async def來定義。需要把這種邏輯用loop.run_in_executor封裝到協(xié)程:
async def c(): loop = asyncio.get_running_loop() return await loop.run_in_executor(None, a)
大家理解了吧?
loop.run_in_executor(None, a)這里面第一個參數(shù)是要傳遞concurrent.futures.Executor實例的,傳遞None會選擇默認的executor:
In : loop._default_executor Out:
當然我們還可以用進程池,這次換個常用的文件讀寫例子,并且用:
async def c3(): loop = asyncio.get_running_loop() with concurrent.futures.ProcessPoolExecutor() as e: print(await asyncio.gather( loop.run_in_executor(e, a), b() )) In : show_perf(c3) ******************** ['A', 'B'] c3 Cost: 1.0218078890000015
下一節(jié):深究python中的asyncio庫-線程池
本文名稱:創(chuàng)新互聯(lián)Python教程:深究Python中的asyncio庫-線程同步
文章來源:http://www.dlmjj.cn/article/djppgio.html


咨詢
建站咨詢
