How does asyncio main thread manage running either the event loop and coroutines at the same time?

Question:

Firs of all, I apologize for my English.
I am learning python asyncio module and I get confused at some point. I learn from the doc that the main purpose of the event loop is to schedule coroutines for running, open newtwork I/O… A running coroutine can yield control back to the event loop by awaiting itself, so correct me if I am wrong, for the above to be possible, the event loop is needed to be always running on the main thread ? If so, how does asyncio manage running either the event loop and the coroutine at the same time on the same thread ? Perhaps there is a mechanism to suspend the event loop and resume it when needed ? Or is the event loop has a dedicated thread (I am not sure)?

Asked By: user13837279

||

Answers:

The event loop

An event loop is the thread that runs the coroutines and also waits on events to happen.

*------------*
^            |
|         wait for next event
|            |
|         get coroutine that handles the event
|            |
|         resume coroutine
|            |
|         coroutine exits or enqueues a new event to wait on
|            |
*------------*

An event can only be handled when the event loop gets back to the top of the loop and asks the OS for any events that need to be handled. Events finishing do not interrupt the current coroutine.

Answered By: SargeATM