Sayalic
Sayalic

Reputation: 7650

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?

Upvotes: 0

Views: 63

Answers (1)

Nick Lee
Nick Lee

Reputation: 5949

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

Upvotes: 2

Related Questions