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

成都創(chuàng)新互聯(lián)主要從事做網(wǎng)站、網(wǎng)站制作、網(wǎng)頁設(shè)計(jì)、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)將樂,十年網(wǎng)站建設(shè)經(jīng)驗(yàn),價(jià)格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):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ù)邏輯轉(zhuǎn)化成一個(gè)協(xié)程,且實(shí)現(xiàn)了并發(fā)。這里要注意細(xì)節(jié),就是函數(shù)a是普通函數(shù),不能寫成協(xié)程,下面的定義是錯(cuò)誤的,不能實(shí)現(xiàn)并發(fā):
async def a(): time.sleep(1) return 'A'
因?yàn)?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)這里面第一個(gè)參數(shù)是要傳遞concurrent.futures.Executor實(shí)例的,傳遞None會(huì)選擇默認(rèn)的executor:
In : loop._default_executor Out:
當(dāng)然我們還可以用進(jìn)程池,這次換個(gè)常用的文件讀寫例子,并且用:
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庫-線程池
本文標(biāo)題:創(chuàng)新互聯(lián)Python教程:深究Python中的asyncio庫-線程同步
瀏覽地址:http://m.5511xx.com/article/djppgio.html


咨詢
建站咨詢
