简体   繁体   中英

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:

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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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