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

1

-2

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?

Vouge answered 11/5 at 15:39 Comment(1)
Does stackoverflow.com/questions/40851872 help?Muffler
F
3

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.

Fp answered 11/5 at 15:49 Comment(3)
I think that key thing is the select I presume that would be significantly better than a sleep I presume it's waiting for an OS event and constant rechecking. Can you add that to your answer if it is true.Vouge
@ArchimedesTrajano: That's already in the answer? select is signaled, it blocks without consuming resources until that happens.Fp
Yup but the part that says "without consuming any resources" is the key phrase that should be added to the answer. I wasn't sure about it until your comment.Vouge

© 2022 - 2024 — McMap. All rights reserved.