Search⌘ K
AI Features

Introduction to Event Loops

Explore the fundamentals of event loops as central control flows that manage message queues for asynchronous programming. Understand how event loops enable programs to efficiently process events from multiple sources, a key concept for building scalable distributed systems with Python.

We'll cover the following...

What is an event loop?

If event loops do not ring a bell, maybe you’ve heard of them under another name, such as message dispatching. An event loop is a central control flow of a program where messages are pushed into a queue, and this queue is consumed by the event loop, dispatching them to appropriate functions.

Note: An event loop is a central control flow of a program where messages are pushed into a queue, and this queue is consumed by the event loop, dispatching them to appropriate functions.

Simplest event loop

A very simplistic form of event loop would be something like this:

Python 3.8
while True: message = get_message() if message == quit: break
process_message(message)

Each time a message, which can also be called an event, is received, it is processed until a final message is received to make the program quit.

This design is quite efficacious as it allows the program to wait and do nothing (as long as get_message is blocking) and waking up as soon as a message is received.

As long as there is only one source of the message, this program can be quite trivial to write. Consuming from a single queue is precisely what distributed programs would do based on queues, as described in Queue-Based Distribution.

However, most programs do not have a single source of messages and events. Moreover, dealing with any event might generate new sources of events, of different types. That means that the program has to handle different sources of events.