import asyncio import time #串行 #asyncio.run() async def say_after(delay, what): await asyncio.sleep(delay) print(what) async def main(): print(f"started at {time.strftime(‘%X‘)}") await say_after(2, ‘hello‘) await say_after(1, ‘world‘) print(f"finished at {time.strftime(‘%X‘)}") asyncio.run(main()) #并行 #asyncio.create_task() async def say_after(delay, what): await asyncio.sleep(delay) print(what) async def main(): task1 = asyncio.create_task( say_after(2, ‘hello‘)) task2 = asyncio.create_task( say_after(1, ‘world‘)) print(f"started at {time.strftime(‘%X‘)}") # Wait until both tasks are completed (should take # around 2 seconds.) await task1 await task2 print(f"finished at {time.strftime(‘%X‘)}") asyncio.run(main())
输出
started at 19:20:48 hello world finished at 19:20:51 started at 19:20:51 world hello finished at 19:20:53
原文地址:https://www.cnblogs.com/sea-stream/p/12163304.html
时间: 2024-11-16 05:49:03