import asyncio
async def func1():
print("Im A")
await asyncio.sleep(3)
print("Im A")
async def func2():
print("Im B")
await asyncio.sleep(2)
print("Im B")
async def func3():
print("Im C")
await asyncio.sleep(4)
print("Im C")
async def main():
# 第一中写法
# f1 = func1()
# await f1 # 一般await挂起操作放在协程对象前面
# f2 = func2()
# await f2
# f3 = func3()
# await f3
# (推荐)第二种写法
tasks = [
func1(),
func2(),
func3()
# python3.8以后用下面的写法
# asyncio.create_task(func1()),
# asyncio.create_task(func2()),
# asyncio.create_task(func3())
]
await asyncio.wait(tasks)
if __name__ == '__main__':
asyncio.run(main())
|