[Python]async/await实现协程

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
posted @ 2023-03-30 15:34  LeoShi2020  阅读(14)  评论(0编辑  收藏  举报