當前位置:科普知識站>IT科技>

python|asyncio

IT科技 閱讀(1.81W)

asyncio 是以協程的模式來編寫併發的庫,使用 async/await 語法。在 IO密集型 的網路程式設計裡,非同步IO 協程 省去了開闢新的執行緒和程序的開銷。asyncio 是 Python3.4 版本引入到標準庫,python3.5 加入了 async/await 特性。下面我們就來分享一下執行協程的幾種方式。

python asyncio

使用 async 宣告協程

async def asyncTask():

    # 協程休眠

    await asyncio.sleep(1)

    print(time.strftime('%X'))

執行協程的幾種方式:

1、asyncio.run() 函式用來在非協程函式中呼叫協程

asyncio.run(asyncTask())

2、使用 await 等待一個協程。

await asyncTask()

3、asyncio.create_task() 用函式將協程打包為一個 Task 排入日程準備執行,返回 asyncio.Task 物件。

此函式 在 Python 3.7 中被加入。

task1 = asyncio.create_task(asyncTask1())task2 = asyncio.create_task(asyncTask2())await task1await task2

4、使用 asyncio.gather() 函式來併發多個協程。

tasks = asyncio.gather(asyncTask1(), asyncTask2())tasks2 = asyncio.gather(*[asyncTask1(), asyncTask2()])await tasksawait tasks2

具體示例:

import asyncioimport time# 定義協程任務async def asyncTask1():

    # 協程休眠

    await asyncio.sleep(1)

    print(time.strftime('%X'), 1)async def asyncTask2():

    await asyncio.sleep(2)

    print(time.strftime('%X'), 2)async def main():

    task1 = asyncio.create_task(asyncTask1())

    task2 = asyncio.create_task(asyncTask2())

    tasks = asyncio.gather(asyncTask1(), asyncTask2())

    tasks2 = asyncio.gather(*[asyncTask1(), asyncTask2()])    await tasks    await tasks2    await task1    await task2

print(time.strftime('%X'), "start")

asyncio.run(main())

print(time.strftime('%X'), "end")

python asyncio 第2張

關於執行協程的方式,我們就瞭解到這啦!