Asyncio
Coroutine (協程 / 微線程)
- 可以暫停將執行權讓給其他 Coroutine 或 Awaitables obj 的函數,等其執行完後再繼續執行,並可以多次的暫停與繼續
- 使用
async def
宣告 - 一定要透過 event loop 排程後才能執行
import asyncio
# 定義一個 coroutine
async def main():
# 程式遇到 await 後,會在此暫停並且轉移到其他 awaitables
await asyncio.sleep(5)
# 等到 await 執行完成後再繼續剩下的工作
return 'hello'
# asyncio.run() 能透過 event loop 執行 coroutine 並回傳其結果
res = asyncio.run(main())
print(res)
Event Loop
- 在背景執行的 thread,不斷地循環進行排程和執行 coroutines、回呼函式等任務
- 適合將 I/O 類型的工作以非同步方式交由 event loop 執行,例如網路通訊、檔案讀寫等。這樣可以讓 event loop 在不同任務之間切換工作,提高效率
import asyncio
async def main():
await asyncio.sleep(5)
return 'hello'
# 建立一個 event loop,並且執行 coroutine
loop = asyncio.get_event_loop()
res = loop.run_until_complete(main())
print(res)
Task
- coroutine 的再包裝,具備取消、新增/刪除 callback 等功能
import asyncio
async def main():
await asyncio.sleep(5)
return 'hello'
loop = asyncio.get_event_loop()
# 建立一個 task
task = loop.create_task(main())
res = loop.run_until_complete(task)
print(res)
Future
代表非同步操作的最終結果