punter147
punter147

Reputation: 312

order of execution in async task

I was experimenting with some basic constructs in python asyncio. I came across the following scenarios:
Snippet 1

import asyncio

async def A():
    await asyncio.sleep(10)
    print("A...")


async def B():
    await asyncio.sleep(15)
    print("B...")

async def main():
    t = asyncio.create_task(A())
    n = asyncio.create_task(B())
    await n
    print("CCDD...")
    await t
    

asyncio.run(main())
Snippet 2
import asyncio

async def A():
    await asyncio.sleep(10)
    print("A...")


async def B():
    await asyncio.sleep(15)
    print("B...")

async def main():
    t = asyncio.create_task(A())
    n = asyncio.create_task(B())
    await n
    await t
    print("CCDD...")

asyncio.run(main())

Snippet 3
import asyncio

async def A():
    await asyncio.sleep(10)
    print("A...")


async def B():
    await asyncio.sleep(15)
    print("B...")

async def main():
    t = asyncio.create_task(A())
    n = asyncio.create_task(B())
    print("CCDD...")
    await n
    await t

asyncio.run(main())

I find it difficult to understand how the output produced by the first two snippets above is the same, but the output produced by the last snippet is different than the first two?
Output of snippets 1, 2

A...
B...
CCDD...

Output of snippet 3
CCDD...
A...
B...

Upvotes: 1

Views: 679

Answers (1)

paxdiablo
paxdiablo

Reputation: 882028

It's all a matter of thinking about the sequencing. First off, n/15/B is always the 15-second task and t/10/A is the 10-second one. For all snippets, that means A will be printed before B, as you start them at roughly the same time.

  • In snippet 1, you start them both then wait for the 15-second task, meaning that both will finish before main prints CCDD (waiting for the 10-second task after that but it's already finished). Hence you see A B CCDD.

  • In snippet 2, you wait for the both the 15-second and 10-second task to finish before main prints CCDD, resulting in A B CCDD.

  • In snippet 3, you start both tasks then immediately print CCDD before waiting for them both. This gives you CCDD A B.

Upvotes: 2

Related Questions