簡介
協程就是CPU中斷
效果上類似生成器函數,yield會記錄迭代位置和狀態然而會中斷執行。
關鍵字
python中Async模塊實現協程操作。
Aysnc:定義協程函數。
await:掛起支持異步的操作
使用
async def p1(): print("比利1") await asyncio.sleep(5) print("比利2") async def p2(): print("van1") await asyncio.sleep(5) print("van2") async def p3(): print("hello1") await asyncio.sleep(5) print("hello2") def main(): loop = asyncio.get_event_loop() task = [ loop.create_task(p1()), loop.create_task(p2()), loop.create_task(p3()) ] loop.run_until_complete(asyncio.wait(task)) if __name__ == '__main__': main()
總結
單線程協程操作
1.async標記協程函數
2.await標記支持異步的阻塞方法
3.通過循環器生成任務列表,執行