Event loop

An event loop, as its name implies, is a loop. What this loop does is, when a new task is supposed to be executed, the event loop queues this task. Now from here, the control shifts to the event loop. When the event loop runs, it checks whether there is some task in its queue or not. If there is a task present, the control switches to the task.

Now, here is the interesting part in the context of the asynchronous execution of tasks. Suppose there are two tasks, namely Task A and Task B, in the queue of the event loop. When the event loop starts executing, it checks the status of the task queue it has. The event queue finds out that there are tasks in its queue. So, the event queue picks up Task A. Now a context switch happens inside the event loop and Task A starts executing. After a certain point of time, Task A makes a call to an external API and gets blocked on network I/O, waiting for the results to arrive from the API. At this point, the event loop takes back the control and puts the task in a waiting state. Now, the event loop starts checking its task queue again. It finds out that there is another task which is waiting inside the queue to be executed, namely Task B. Now, the event queue picks up Task B, a context switch happens and Task B starts executing. After a certain time, the Task B finishes its execution and the results are generated. Once the results are generated and sent back, the event loop removes the task from the task queue. At this point, the control again comes back to the event queue. Now it finds that Task A which was in blocked state has completed its I/O and is ready for execution again. A context switch happens and control shifts to the execution of Task A. This time, Task A completes its execution and the results are generated and sent back. With this, Task A also gets removed from the event loop queue. The control transfers back to the event loop, which now does not have any other task to execute. The event loop now enters a waiting state, awaiting the arrival of new tasks.

That's how the life of an event queue is spent. It acts as a core part of the process of asynchronous operations and is responsible for the queuing, execution, prioritization, and canceling of tasks.