asyncio异步协程写法
在python3.7之前
async def f1(num):
print("f1 start")
await asyncio.sleep(num)
print("f1 end")
async def f2(num):
print("f3 start")
await asyncio.sleep(num)
print("f3 end")
async def f3(num):
print("f3 start")
await asyncio.sleep(num)
print("f3 end")
async def main():
print(int(time.time()))
loop = asyncio.get_event_loop()
task1 = loop.create_task(f1(1)) # create_task是asyncio.get_event_loop()创建
task2 = loop.create_task(f2(2))
task3 = loop.create_task(f3(3))
await task1
await task2
await task3
print(int(time.time()))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()
python3.7之后(兼容3.7之前的)
async def f1(num):
print("f1 start")
await asyncio.sleep(num)
print("f1 end")
async def f2(num):
print("f3 start")
await asyncio.sleep(num)
print("f3 end")
async def f3(num):
print("f3 start")
await asyncio.sleep(num)
print("f3 end")
async def main():
print(int(time.time()))
task1 = asyncio.create_task(f1(1)) # 直接acyncio.create_task
task2 = asyncio.create_task(f2(2))
task3 = asyncio.create_task(f3(3))
await task1
await task2
await task3
# 上面是异步,下面同步
# await f1(1)
# await f2(2)
# await f3(3)
print(int(time.time()))
if __name__ == '__main__':
asyncio.run(main()) # 直接asyncio.run 即可
输出
1623983932
f1 start
f3 start
f3 start
f1 end
f3 end
f3 end
1623983935