您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關(guān)Python中的asyncio庫-線程同步,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結(jié)了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。
前面的代碼都是異步的,就如sleep,需要用asyncio.sleep而不是阻塞的time.sleep,如果有同步邏輯,怎么利用asyncio實現(xiàn)并發(fā)呢?答案是用run_in_executor。在一開始我說過開發(fā)者創(chuàng)建 Future 對象情況很少,主要是用run_in_executor,就是讓同步函數(shù)在一個執(zhí)行器( executor)里面運行。
同步代碼
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)化成一個協(xié)程,且實現(xiàn)了并發(fā)。這里要注意細(xì)節(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會選擇默認(rèn)的executor:
In : loop._default_executor Out: <concurrent.futures.thread.ThreadPoolExecutor at 0x112b60e80>
當(dāng)然我們還可以用進(jìn)程池,這次換個常用的文件讀寫例子,并且用:
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
看完上述內(nèi)容,你們對Python中的asyncio庫-線程同步有進(jìn)一步的了解嗎?如果還想了解更多知識或者相關(guān)內(nèi)容,請關(guān)注億速云行業(yè)資訊頻道,感謝大家的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。