pythontaskcoroutine

Why python runs the unused task1


In this python code that is mostly sample code for tasks and routins:

import asyncio

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


async def main():
    task1 = asyncio.create_task(
        say_after(1, 'hello'))

    task2 = asyncio.create_task(
        say_after(2, 'world'))

    await task2

asyncio.run(main())

I expect:

world

but I get:

hello
world

What am I doing wrong?


Solution

  • Await just stops your program and actually waits until the asynchronous task is finished. The chronology looks like this:

    1. Run main
    2. First task gets a delay of 1s and will output 'hello'
    3. Second tasks gets a delay of 2s and will output 'world'
    4. We wait for the second task to finish
    5. Program ends with output from both tasks

    Now if we switch await task2 to await task1 it will look like this:

    1. Run main
    2. First task gets a delay of 1s and will output 'hello'
    3. Second tasks gets a delay of 2s and will output 'world'
    4. We wait for the first task to finish. Except this time first task will be finished before the second one.
    5. Program ends with output of only 'hello'