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
Here is what happens on a timeline:
After 0 seconds:
task1startstask2starts- output
---0 await task1blocks
After 2 seconds:
task2printsBand finishes
After 3 seconds:
task1printsAand finishesawait task1returns- output
---1 await task2returns (task was already finished 1 second ago)
1 Comment
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.sleep(2) wakes up earlier than sleep(3) but I think something would be seriously wrong if it didn't.print is implemented internally as async and could take up to 4 seconds to complete could produce these results (silly example).