G
G
Grandma Luda2021-10-28 13:13:02
Python
Grandma Luda, 2021-10-28 13:13:02

Why doesn't await switch coroutines?

I understand that await switches the attention of the event_loop loop from one coroutine to the next, but in my case this does not work

import asyncio

async def c():
    pass

async def a():
    print("start a")
    await c()
    print("finish a")

async def b():
    print("start b")
    await c()
    print("finish b")

async def main():
    loop.create_task(a())
    print("create task")
    loop.create_task(b())

loop = asyncio.new_event_loop()
loop.run_until_complete(main())
loop.run_forever()


displays
create task
start a
finish a
start b
finish b


but i'm waiting for the output
create task
start a
start b
finish a
finish b

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
Roman Kitaev, 2021-10-28
@deliro

in def c do await asyncio.sleep(0.1). Otherwise, you just run into the state machine of the event loop. And there everything is just logical and the conclusion is correct.
Moreover, it is correct to run asyncio.run(main()) and the explicit use of loop is deprecated

S
shurshur, 2021-10-28
@shurshur

asyncio does not guarantee in any way the order in which the functions will be executed and the switch to the next one will be performed. In this example, for example, a() will be run and nothing about the run of b() will be known to the runtime yet. Then c() will run, exit quickly, and terminate a().
There is little point in such a test - everything happens very quickly here. For experimentation, I would recommend inserting asyncio.sleep into the c function so that it does not complete so quickly, and also during this wait, the next task would be guaranteed to be selected - in this case, main () continued execution.

B
baynic, 2021-10-28
@baynic

A switch occurs when an event occurs that requires a wait. In the c() function, replace pass with await asyncio.sleep(1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question