[Python]async/await实现协程

发布时间 2023-03-30 15:35:52作者: LeoShi2020
import asyncio
async def f1():
    print(1)
    await asyncio.sleep(2)
    print(2)
async def f2():
    print(3)
    await asyncio.sleep(2) # 等 可以等待的对象
    print(4)

tasks = [
    asyncio.ensure_future(f1()),
    asyncio.ensure_future(f2())
]
loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.wait(tasks)) 

# 打印结果:1 3 -睡2s- 2 4