日本综合一区二区|亚洲中文天堂综合|日韩欧美自拍一区|男女精品天堂一区|欧美自拍第6页亚洲成人精品一区|亚洲黄色天堂一区二区成人|超碰91偷拍第一页|日韩av夜夜嗨中文字幕|久久蜜综合视频官网|精美人妻一区二区三区

RELATEED CONSULTING
相關咨詢
選擇下列產(chǎn)品馬上在線溝通
服務時間:8:30-17:00
你可能遇到了下面的問題
關閉右側工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
Python中的asyncio庫-線程同步

今天就跟大家聊聊有關Python中的asyncio庫-線程同步,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內(nèi)容,希望大家根據(jù)這篇文章可以有所收獲。

我們提供的服務有:網(wǎng)站制作、做網(wǎng)站、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認證、禹州ssl等。為近千家企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務,是有科學管理、有技術的禹州網(wǎng)站制作公司

前面的代碼都是異步的,就如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ù)邏輯轉化成一個協(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

看完上述內(nèi)容,你們對Python中的asyncio庫-線程同步有進一步的了解嗎?如果還想了解更多知識或者相關內(nèi)容,請關注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝大家的支持。


本文標題:Python中的asyncio庫-線程同步
鏈接地址:http://www.dlmjj.cn/article/pppics.html