When I run it on cpython 3.6, the following program prints hello world
a single time and then spins forever.
As a side note, uncommenting the await asyncio.sleep(0)
line causes it to print hello world
every second, which is understandable.
import asyncio
async def do_nothing():
# await asyncio.sleep(0)
pass
async def hog_the_event_loop():
while True:
await do_nothing()
async def timer_print():
while True:
print("hello world")
await asyncio.sleep(1)
loop = asyncio.get_event_loop()
loop.create_task(timer_print())
loop.create_task(hog_the_event_loop())
loop.run_forever()
This behavior (printing hello world
a single time) makes sense to me, because hog_the_event_loop
never blocks and therefore has no need to suspend execution. Can I rely on this behavior? When the line await do_nothing()
runs, is it possible that rather than entering the do_nothing()
coroutine, execution will actually suspend and resume timer_print()
, causing the program to print hello world
a second time?
Put more generally: When will python suspend execution of a coroutine and switch to another one? Is it potentially on any use of the await
keyword? or is it only in cases where this results in an underlying select
call (such as I/O, sleep timers, etc)?
Additional Clarification
I understand that if hog_the_event_loop
looked like this, it would certainly never yield execution to another coroutine:
async def hog_the_event_loop():
while True:
pass
I'm trying to specifically get at the question of whether await do_nothing()
is any different than the above.