python asyncio run_forever or while True is similar but it is a "should I do this..." question.
I am more trying to understand if the internals of python asyncio
is basically a
while True:...time.sleep(1)
(or more precisely... while not stopped:
loop.
Does it use also use sleep
to prevent spin waits?
Check the source code? If you're in IPython, it's pretty trivial:
>>> import asyncio
>>> loop = asyncio.get_event_loop()
>>> loop.run_forever??
The core of the loop (on my 3.11 install) is:
while True:self._run_once()if self._stopping:break
So yep, it's a while True:
loop. You can check loop._run_once??
to see the source code for that, and it's much more complicated, but short version is that it's not a sleep, it's a select
call that blocks (not polls) until some async task completes, adds itself to the queue, and signals the event loop that there is work to do.