1

I am trying to learn native coroutine. I run the above example and I don't understand it.

Here is the example.

import asyncio

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

async def main():
    task1 = asyncio.create_task(
        say_after(3, "A")
    )
    
    task2 = asyncio.create_task(
        say_after(2, "B")
    )

    print("----0")
    await task1
    print("----1")
    await task2

asyncio.run(main())

I heard that await waits for the task to finish. I expected to be printed in the order

A
B
----1

However, in the example above, ----1 is output after both B and A are printed.

The following is the output printed.

----0
B
A
----1

Why is this output created?

Do you know a site that has a collection of useful examples for studying native coroutine?

2 Answers 2

2

Here is what happens on a timeline:

After 0 seconds:

  • task1 starts
  • task2 starts
  • output ---0
  • await task1 blocks

After 2 seconds:

  • task2 prints B and finishes

After 3 seconds:

  • task1 prints A and finishes
  • await task1 returns
  • output ---1
  • await task2 returns (task was already finished 1 second ago)
Sign up to request clarification or add additional context in comments.

1 Comment

Why ------1 comes at the end? I thought the output should be ----0 ------1 B A. What part am I missing here?
0

There's no guarantee in what order the async tasks are run. The only guarantee you have is when you await a task execution in main will stop until that task is complete. The following are all valid outputs of your program and you can't assume that you will get any one in particular:

A
B
----0
----1
B
A
----0
----1
----0
A
B
----1
----0
B
A
----1
A
----0
B
----1
B
----0
A
----1
A
----0
----1
B
----0
A
----1
B

5 Comments

---0 will always come before A and B because the two tasks sleep for 2 or 3 seconds, respectively, while the main function runs. A will always come after B because task2 wakes up 1 second earlier than task1.
tbh I don't know if it is guaranteed that sleep(2) wakes up earlier than sleep(3) but I think something would be seriously wrong if it didn't.
@mkrieger1 In practice, almost certainly so. But there's no guarantee. A system where print is implemented internally as async and could take up to 4 seconds to complete could produce these results (silly example).
That's a convincing argument.
Why ------1 comes at the end? I thought the output should be ----0 ------1 B A. What part am I missing here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.