280 Eventloops (asyncio)
Event loop
The concept of event loops is fundamental in event-driven programming and is often used in asynchronous programming models. An event loop is a programming construct that allows an application to efficiently handle and respond to various events or tasks.
At its core, an event loop continuously checks for events or tasks that are pending and dispatches them to appropriate handlers or callbacks. It enables an application to execute multiple tasks concurrently without blocking the execution of other tasks. The event loop runs indefinitely, ensuring that events are processed as they occur.
Overview of the working of a typical event loop
Initialization: The event loop is initialized, and any necessary setup is performed.
Waiting for events: The event loop enters a loop where it waits for events to occur. These events can include user input, network activity, timer expirations, or any other kind of asynchronous event.
Event detection: As events occur, the event loop detects them and places them in a queue or dispatches them for handling.
Event handling: The event loop retrieves events from the queue one at a time and invokes the appropriate event handlers or callbacks associated with those events. The handlers can perform the necessary processing or initiate further actions.
Non-blocking execution: Event handlers or callbacks are typically designed to execute non-blocking code. This means that if an event handler encounters a time-consuming task, it can delegate that task to a separate thread or use asynchronous techniques like promises, futures, or coroutines to avoid blocking the event loop.
Return to waiting: After an event is processed, the event loop returns to waiting for more events. This cycle continues until the application is terminated or instructed to stop.
Event loops are widely used in various programming frameworks and libraries to build responsive and scalable applications. They are particularly useful in scenarios where I/O operations or interactions with external systems are involved, as they allow the application to handle multiple concurrent operations efficiently without wasting system resources on waiting for each operation to complete.
Python AsyncIO
A popular event loop implementations is asyncio in Python, which provides event-driven and coroutine-based programming models. AsyncIO was introduced in Python 3.5, since then a lot of improvements have been made. The asyncio framework in Python is quite new and thus the documentation is still a little bit poor. A good starting point is the official Python documentation
async / await
The Python asyncio introduces two new keywords:
async: to define a coroutineawait: to pause the current coroutine and wait for the execution of another coroutine