python面試之異步編程

WHAT

以進(jìn)程、線程、協(xié)程、函數(shù)/方法作為執(zhí)行任務(wù)程序的基本單位,結(jié)合回調(diào)、事件循環(huán)、信號(hào)量等機(jī)制,以提高程序整體執(zhí)行效率和并發(fā)能力的編程方式。

解決方案

通過(guò)協(xié)程

WHY

在一個(gè)線程中,如果遇到IO等待,利用該空閑時(shí)間,再去干點(diǎn)其他的事。

WHAT

并不是計(jì)算機(jī)系統(tǒng)提供(進(jìn)程,線程),而是程序員人為創(chuàng)造的。
用戶(hù)態(tài)內(nèi)的上下文切換技術(shù)。
簡(jiǎn)而言之,就是通過(guò)一個(gè)線程實(shí)現(xiàn)代碼之間的相互切換。

HOW

方法1. 通過(guò)第三方模塊,如:gevent
方法2. 通過(guò)關(guān)鍵字yield

def func():
    yield 1
    yield from func2()
    yield 2


def func2():
    yield 3
    yield 4


f1 = func()
for item in f1:
    print(item)

方法3. 通過(guò)python標(biāo)準(zhǔn)庫(kù),如:asyncio (py3.4)
遇到IO阻塞,可自動(dòng)切換

import asyncio


@asyncio.coroutine
def func1():
    print(1)
    yield from asyncio.sleep(2)  # 遇到IO耗時(shí)操作時(shí)(需要2秒),自動(dòng)切換到task中的其他任務(wù)
    print(2)


@asyncio.coroutine
def func2():
    print(3)
    yield from asyncio.sleep(1)  # 遇到IO耗時(shí)操作時(shí)(需要1秒),自動(dòng)切換到task中的其他任務(wù)
    print(4)


tasks = [
    asyncio.ensure_future(func1()),
    asyncio.ensure_future(func2()),
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

方法4. 通過(guò)關(guān)鍵字:async,await (py3.5)【推薦】
跟方法3工作的原理一致,只是方便了寫(xiě)法

import asyncio


async def func1():
    print(1)
    await asyncio.sleep(2)  # 遇到IO耗時(shí)操作時(shí)(需要2秒),自動(dòng)切換到task中的其他任務(wù)
    print(2)


async def func2():
    print(3)
    await asyncio.sleep(1)  # 遇到IO耗時(shí)操作時(shí)(需要1秒),自動(dòng)切換到task中的其他任務(wù)
    print(4)


tasks = [
    asyncio.ensure_future(func1()),
    asyncio.ensure_future(func2()),
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容