Internally, is asyncio run_forever() basically a while True loop?

Question:

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?

Asked By: Archimedes Trajano

||

Answers:

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.

Answered By: ShadowRanger
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.