简体   繁体   English

如何使用 Python async/await 同时运行两个任务?

[英]How to run two task concurrently with Python async/await?

Code:代码:

import asyncio


async def f1():
    print('f1:1')
    await asyncio.sleep(2)
    print('f1:2')


async def f2():
    print('f2:1')
    await asyncio.sleep(2)
    print('f2:2')


async def f():
    await f1()
    await f2()


asyncio.run(f())

Result:结果:

f1:1
f1:2
f2:1
f2:2

What I expected is run f1 and f2 concurrently, and with result:我期望的是同时运行f1f2 ,结果是:

f1:1
f2:1
f1:2
f2:2

So could anyone please give me some suggestion?那么有人可以给我一些建议吗?

Use gather() :使用收集()

import asyncio


async def f1():
    print('f1:1')
    await asyncio.sleep(2)
    print('f1:2')


async def f2():
    print('f2:1')
    await asyncio.sleep(2)
    print('f2:2')


async def f():
    await asyncio.gather(f1(), f2())


asyncio.run(f())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM