當前位置:科普知識站>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張

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