基本概念:
asyncio 是以協程的模式來編寫並發的庫,使用 async/await 語法。
在 IO密集型 的網絡編程里,異步IO 協程 省去了開辟新的線程和進程的開銷。
asyncio 是 Python3.4 版本引入到標准庫,python3.5 加入了 async/await 特性。
使用 async 聲明協程
async def asyncTask():
# 協程休眠
await asyncio.sleep(1)
print(time.strftime('%X'))
運行協程的幾種方式:
- asyncio.run() 函數用來在非協程函數中調用協程
asyncio.run(asyncTask())
- 使用 await 等待一個協程。
await asyncTask()
- asyncio.create_task() 用函數將協程打包為一個 Task 排入日程准備執行,返回 asyncio.Task 對象。
此函數 在 Python 3.7 中被加入。
task1 = asyncio.create_task(asyncTask1())
task2 = asyncio.create_task(asyncTask2())
await task1
await task2
- 可以使用 asyncio.gather() 函數來並發多個協程。
tasks = asyncio.gather(asyncTask1(), asyncTask2())
tasks2 = asyncio.gather(*[asyncTask1(), asyncTask2()])
await tasks
await tasks2
整體示例:
import asyncio
import 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")
輸出: