-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?

1

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

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.
@ArchimedesTrajano: That's already in the answer? select is signaled, it blocks without consuming resources until that happens.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.