Search code examples
pythonasynchronousasync-awaitpython-asyncio

Why is my asyncio task not running concurrently in Python?


I'm using Python's asyncio module to run multiple tasks concurrently. However, my tasks seem to be running sequentially rather than concurrently, causing delays in my program. I'm not sure why this is happening.

What You Have Tried: I wrote a simple script to test concurrency with asyncio. I expect the tasks to run in parallel, but they appear to run one after the other. Here’s the code I'm using:

import asyncio
import time

async def say_after(delay, message):
    await asyncio.sleep(delay)
    print(message)

async def main():
    print(f"started at {time.strftime('%X')}")

    await say_after(2, 'hello')
    await say_after(1, 'world')

    print(f"finished at {time.strftime('%X')}")

asyncio.run(main())

I expect the output to be:

started at <time>
hello
world
finished at <time>

with a total delay of about 2 seconds.

The actual output is:

started at <time>
hello
world
finished at <time>

but the total delay is about 3 seconds.


Solution

  • I think the issue might be due to how you´re awaiting each say_after task sequentially in the main function? To run the tasks concurrently you´d need to start the tasks and then await them all together, i.e., using create_task. Like this:

    async def main():
        print(f"started at {time.strftime('%X')}")
        task1 = asyncio.create_task(say_after(1, 'hello'));
        task2 = asyncio.create_task(say_after(2, 'world'));
        await task1;
        await task2;
        print(f"finished at {time.strftime('%X')}")
    

    The output for this is:

    started at 00:15:37
    hello
    world
    finished at 00:15:39