[Python] Asyncio order of execution vs trio order of execution

Discussão em 'Python' iniciado por Stack, Julho 5, 2025.

  1. Stack

    Stack Membro Participativo

    I executed the same code with asyncio and trio more than ones. The order of execution for asyncio seemed to be preserved on every run but not with Trio. Any particular reason that this happens?

    asyncio code


    async def greet():
    print("Greet: Hello")
    await asyncio.sleep(1)
    print("Greet: World")

    async def countdown():
    print("Countdown: 3")
    await greet()#sleep(0.5)
    print("Countdown: 2")
    await asyncio.sleep(0.5)
    print("Countdown: 1")

    async def main():
    # Run both coroutines concurrently
    await asyncio.gather(greet(), countdown())

    asyncio.run(main())


    execution result over many runs is same:


    Greet: Hello
    Countdown: 3
    Greet: Hello
    Greet: World
    Greet: World
    Countdown: 2
    Countdown: 1

    Trio code


    import trio

    async def greet():
    print("Greet: Hello")
    await trio.sleep(1)
    print("Greet: World")

    async def countdown():
    print("Countdown: 3")
    await greet()
    print("Countdown: 2")
    await trio.sleep(0.5)
    print("Countdown: 1")

    async def main():
    async with trio.open_nursery() as nursery:
    nursery.start_soon(greet)
    nursery.start_soon(countdown)

    trio.run(main)

    Execution order changes with runs


    Countdown: 3
    Greet: Hello
    Greet: Hello
    Greet: World
    Countdown: 2
    Greet: World
    Countdown: 1

    I want understand why this difference. Does this mean trio really does not care what order it executes the coroutines and asyncio does?

    Continue reading...

Compartilhe esta Página