Definition
An event loop is the part of a program that repeatedly takes the next event from a queue and runs the handler registered for that event, one handler at a time. An event is a record that something has happened, such as a packet arriving or a timer expiring. A handler is a function that the program has registered to run for one kind of event. The loop starts the next handler only after the current one returns, so a handler that does not return keeps every other event waiting.
The idea
A small sensor device must react to a radio packet, a button press, a timer and a finished measurement, none of which comes at a predictable moment. One design gives each source its own thread, a sequence of instructions that the operating system schedules independently of the others, and protects shared data with locks, variables that let only one thread at a time use the data. The event loop is the other design: one thread and one queue. Each source only puts a record of what happened into the queue, and the single thread takes the records out one by one and runs the matching handler.
Because the handlers of one loop never run at the same time, data that only those handlers use needs no lock: no other handler of the loop can start in the middle of one. The price is that while a handler runs, nothing else on that loop happens.
A single clerk at a counter is a fair picture. The clerk serves customers in turn, finishing with one before calling the next, so a long request delays everyone behind it. Suppose the clerk, while serving customer A, waits for a letter in a mail tray that only the clerk empties, and only between customers. The letter lies in the tray, and the clerk waits forever. The picture stops being accurate in one respect: a real clerk would notice the letter, and a program does not.
How it works
An event loop repeats four steps.
Wait until the queue holds an event. With an operating system, the loop asks the operating system, with a call such as
selectorepoll, to wake it when one of its network connections or files is ready or when its next timer is due. On a microcontroller §6.1, the loop may stop the processor until the next interrupt §6.11, a hardware signal from a device.Take the next event: the oldest one in a first-in, first-out (FIFO) queue §14.14, or the most urgent one in a priority queue §14.16.
Dispatch: call the handler registered for that kind of event. A handler is a callback §14.22, a function that one part of a program hands to another, which calls it later.
Repeat when the handler returns.
Other parts of the system only fill the queue. An interrupt service routine §6.12 (ISR), the routine the processor runs when a device raises an interrupt, or another thread does the minimum work and puts an event into the queue; the loop’s thread runs the handler later. The loop cannot stop a handler part-way: each handler runs until it returns. This is cooperative multitasking §6.37, in which a piece of work gives up the processor only by its own action. A thread that runs queued jobs one at a time, such as the system work queue §6.36 of the Zephyr real-time operating system §6.33, is an event loop too.
A handler must therefore not wait for anything slow. An operation such as sending a request and receiving its reply is split. The first handler starts the operation, stores a record of what remains to be done, called a continuation, and returns. The record often holds the state of a small state machine §8.33, that is, which of a fixed set of stages the operation has reached, such as waiting for the reply to request 7. The reply arrives as an event, and its handler finds the record and finishes the work. This is asynchronous completion §9.28: the end of an operation is reported by a later event, not by the return of the call that started it.
Coroutines let one function express such a split. A coroutine is a function that can suspend at marked points and later resume where it stopped, with its local variables intact. In JavaScript and in Python’s §12.23 asyncio library, the keyword await marks such a point. A coroutine that awaits a result that is not ready suspends, and control returns to the loop, which runs other work. When the result is ready, the loop resumes the coroutine just after the await. In asyncio, a coroutine that the loop runs is wrapped in a task, and plain functions can be scheduled on the loop as callbacks. There an await returns control to the loop only if it actually suspends; awaiting a result that is already available, or a coroutine that finishes without suspending, does not.
Two rules follow.
Where other code of the loop can run. Another handler, task or callback of the same loop runs only where the running code gives control back: at a return, or at an
awaitthat suspends. A coroutine that sends data in chunks, with oneawaitper chunk, can be interrupted by a status callback of its loop only at thoseawaitpoints, never between two statements without one. The callback may therefore update data it shares with the coroutine without a lock, provided the coroutine never leaves that data half updated across anawait.What a handler must not do. A handler must not make a blocking call, a call that keeps the thread waiting, such as a sleep or a wait for a lock. In Python,
time.sleep(1)inside a coroutine stops the whole loop for 1 second, whereasawait asyncio.sleep(1)suspends only that coroutine. Work that cannot avoid a blocking call goes to another thread, for example withasyncio.to_thread, and its result returns to the loop.
asyncio.wait_for and, since Python 3.11, asyncio.timeout put a timeout §9.34, a limit on how long to wait, around an await. When the time runs out, asyncio cancels the awaited work: it raises the exception CancelledError inside the coroutine doing that work, at the await where that coroutine is suspended; the coroutine’s clean-up code, such as its finally blocks, runs; and the code that set the timeout then receives TimeoutError. Cancellation §9.29, a request that a started operation stop early, therefore also takes effect only at an await.
Worked example
A handler that waits for its own loop. Handler A runs at time 0 ms, sends a request to a sensor, and then checks a variable reply_ready over and over. The reply arrives at 5 ms, and the radio’s ISR puts event B, reply received, into the queue; B’s handler sets reply_ready. Now A returns only after reply_ready is set; reply_ready is set only when B’s handler runs; and B’s handler runs only after A returns. The waits form a cycle, so the program stops forever. This is a deadlock §9.14: a state in which activities wait for each other in a cycle, so none can go on. No second processor core is involved; the cycle lies in the loop’s own order of work.
A timeout of 100 ms on A’s wait does not repair this. At 100 ms A reports a failure although the reply came at 5 ms, every other event has waited until then, and B’s handler finally runs and finds nobody waiting. The repair is for A to store the continuation waiting for the reply to request 7 and return, at 1 ms. The loop handles other events. At 5 ms it takes B, and B’s handler finds the record and finishes the work. A timer event at 100 ms removes the record if no reply has come, so a missing reply is still reported.
Where a coroutine can be interrupted. Two asyncio tasks each add 1 to a shared counter count, which starts at 0, with three lines: x = count, then await asyncio.sleep(0), which suspends the task for one turn of the loop, then count = x + 1. Task 1 reads 0 and suspends. Task 2 reads 0 and suspends. Task 1 resumes and writes . Task 2 resumes and writes . The counter ends at 1, not 2: one addition is lost. Without the await, each task reads and writes without a pause, and the counter ends at 2 with no lock at all.
Stated precisely
Let a loop run on one thread. Call a step the stretch of a handler’s execution from its start or resumption to its return or to an await that suspends. Assume that (1) every handler, task and callback of runs on ’s thread, and (2) no step starts a nested loop that dispatches ’s events before the step ends. Then three guarantees hold.
Exclusion. At most one step of runs at any instant, and steps never interleave. Data that only steps of use needs no lock, provided every rule that the data must satisfy holds again at the end of each step.
Progress. A queued event is dispatched only after the running step ends, so a step that waits for a condition that only a later step of can make true never ends.
Waiting time. With a first-in, first-out queue, let an event arrive while the running step has milliseconds left, behind queued events whose steps take milliseconds. The event’s handler starts milliseconds after the arrival, plus the loop’s own time per event. That time has an upper bound only if every step’s duration and the queue’s length are bounded.
Assumption 1 fails when a library calls a callback from a thread of its own. Assumption 2 fails in toolkits for graphical user interfaces that run a nested loop while a dialog window is open. In both cases other code can run inside a step, and exclusion is lost.
Limits and common mistakes
Running handlers one at a time protects shared state only from the other handlers of this loop; interrupts, other threads and devices that access memory directly can still change it. Data shared with an ISR still needs interrupts disabled around each access, an atomic operation §9.8, which other code cannot observe half done, or a queue built for that use. Buffers that a device fills by direct memory access §4.36 (DMA), without the processor, need the same care.
A rule that must hold across an await is not protected, as the lost addition in the example shows. asyncio.Lock keeps several steps together; it excludes other tasks of the same loop without blocking the thread.
A long computation delays the loop without any deadlock. A handler that computes for 200 ms delays every event behind it by 200 ms: this is head-of-line blocking §9.19. Moving the computation to another thread removes the delay, unless that thread itself waits for the loop.
By itself, an event loop does not make a real-time system §6.34, one that must respond within stated time limits. It meets such limits only if the worst-case execution time §9.33 of every step, meaning the longest time that step can take, and the rate of arriving events are bounded.
If events arrive faster than handlers finish, an unbounded queue grows until memory runs out. A bounded queue §9.31 must drop, reject or merge events when it is full, and the program must state which.
A timeout ends a wait; it does not stop the other party. A reply can still arrive after the timeout, so the handler must recognize a late reply, for example by its request number, and discard it.
A callback that a library calls from a thread of its own is not on the loop, even if it looks like a handler. In asyncio it must pass its work to the loop with loop.call_soon_threadsafe.
Questions answered
Can a handler block while waiting for an event that the same loop must deliver?
No: a handler that blocks while waiting for an event that its own loop must deliver deadlocks the loop. To block means to keep the loop’s thread waiting without returning. The loop runs the handler of the awaited event only after the waiting handler returns, and the waiting handler returns only after that event has been handled, so neither can go on. A timeout ends the wait but does not deliver the event, and every other event of the loop waits meanwhile.
The handler must give control back to the loop instead. It can store a record of what remains to be done and return, so that the handler of the awaited event finishes the work. In a coroutine, it can await the event, which suspends only the coroutine and lets the loop run other handlers. A blocking wait is safe only if something other than the waiting loop produces and delivers the awaited event.
Related entries: Queue and FIFO (§14.14), Callback (§14.22), Queueing delay (§14.38), Data plane versus control plane (§1.39), Deadlock (§9.14), Asynchronous completion (§9.28), Cancellation (§9.29), Head-of-line blocking (§9.19), Cooperative and preemptive scheduling (§6.37).