Programming Search⌘K

Conceptcore

Event-driven programming

Also called event loop, event handlers, callbacks on events, listeners, reactor pattern, GUI event programming.

Event-driven programming structures a program as handlers that an event loop calls when events happen, such as input, timers or ready sockets, so the events decide the order of work.

Applies to
core-languages

Idea

Event-driven programming structures a program as a set of handlers that run when events happen. An event is a fact that the program must react to: a key press, a click, data on a socket, a timer that expires or a message from another part of the program. An event loop waits for events and calls the handlers that the program registered for them. John Ousterhout summarized the model in 1995 in a list: "One execution stream: no CPU concurrency. Register interest in events (callbacks). Event loop waits for events, invokes handlers. No preemption of event handlers. Handlers generally short-lived."1 The example below is a small event loop with a simulated clock:

import heapq
import itertools
from collections import defaultdict

handlers = defaultdict(list)
queue = []
order = itertools.count()
now = 0


def on(event, handler):
    handlers[event].append(handler)


def emit(event, data=None, delay=0):
    heapq.heappush(queue, (now + delay, next(order), event, data))


def run():
    global now
    while queue:
        now, _, event, data = heapq.heappop(queue)
        for handler in handlers[event]:
            handler(data)


def on_click(button):
    print(f"t={now} click on {button}")
    if button == "save":
        emit("saved", "report.txt", delay=30)


on("click", on_click)
on("click", lambda button: print(f"t={now} log: {button}"))
on("saved", lambda name: print(f"t={now} saved {name}"))
on("tick", lambda n: print(f"t={now} tick {n}"))

emit("click", "save", delay=10)
emit("tick", 1, delay=20)
emit("click", "open", delay=25)
emit("tick", 2, delay=40)
run()
Output
t=10 click on save
t=10 log: save
t=20 tick 1
t=25 click on open
t=25 log: open
t=40 tick 2
t=40 saved report.txt

The program does not decide the order of its work. The events decide it. The main part of the program only registers handlers and starts the loop. A handler can emit new events, as on_click does when it schedules the saved event, and the loop delivers them later. Two handlers for the same event run in the order of registration.

How it works

The event loop. At its center, an event-driven program has a loop: wait for the next event, find the handlers for it, call them, and repeat. The loop is often in a library or in the runtime, not in the program. The HTML standard requires it of browsers: "To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section."2 Node.js uses the same model for servers, and the Node.js documentation says that the event loop "is what allows Node.js to perform non-blocking I/O operations", even though one JavaScript thread runs the code by default.3

Registration. A program connects a handler to an event source: addEventListener in the browser, on in Node.js, += on a C# event, a listener object in Java, a callback stored with a file descriptor in Python's selectors. The source keeps a list of handlers and calls each one when the event happens. This is the observer pattern, with the loop as the part that decides when.

Waiting for many sources. A loop that serves sockets must wait for all of them at once. The operating system provides calls for this: select and poll on POSIX systems, epoll on Linux, kqueue on the BSDs and macOS, and I/O completion ports on Windows. The loop gives the kernel a list of descriptors, sleeps until one is ready, and then calls the handler for each ready descriptor. Timers are kept in a priority queue sorted by due time, and the loop uses the time to the next timer as the limit of its wait.

Run to completion. In most event loops, a handler runs until it returns, and no other handler starts in between. MDN describes the result for JavaScript: "whenever a function runs, it cannot be preempted and will run entirely before any other code runs".4 A handler can therefore update shared data without locks. The cost is that a slow handler delays every other event. MDN states the downside: "if a job takes too long to complete, the web application is unable to process user interactions like click or scroll."4

State across events. A handler must return to let the loop continue, so it cannot keep local variables from one event to the next. Ousterhout listed this as a problem of the model: a program "can't maintain local state across events (handler must return)."1 Programs keep the state in objects or closures, or in an explicit state machine. Callbacks, promises and async/await are steps that make this easier: an async function looks like straight-line code, and the compiler splits it into handlers that the loop calls when each awaited result is ready.

In languages

LanguageVerdictNote
PythonStandard library
C++Idiom
JavaStandard library
CIdiom
C#Native
JavaScriptNative
TypeScriptNativeAs JavaScript; the DOM and Node.js type definitions give a type to each event and to the argument of its listener.
GoIdiom
RustIdiom
KotlinStandard libraryJava listener interfaces and the Swing event thread; coroutines with Flow for streams of events; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLNativeA trigger runs statements when an INSERT, UPDATE or DELETE changes a table.
BashIdiomTrap runs a handler when the shell receives a signal, and a read loop over a pipe or a FIFO handles lines as they arrive.
PowerShellNativeRegister-ObjectEvent and Register-EngineEvent subscribe a script block to .NET and engine events; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLNativeElements fire events such as click and input, and attributes such as onclick or script listeners handle them; the browser runs the event loop.
CSSDoes not applyPseudo-classes such as :hover and :focus change styles when the state changes, but CSS has no handlers.
Regular expressionsDoes not applyA regular expression matches text and has no events or handlers.
Language Verdict Mechanism
Python stdlib selectors, asyncio event loop, tkinter
JavaScript native the host event loop, addEventListener, EventEmitter
TypeScript native as JavaScript, with typed events
Java stdlib listener interfaces, java.beans, the Swing event thread
Kotlin stdlib Java listeners; Flow in the coroutines library
C# native event members of delegate type
Go idiom a loop over select on channels
Rust idiom a loop over a channel with an enum of events; async runtimes in crates
C idiom poll or select with function pointers
C++ idiom a queue of std::function handlers; Boost.Asio, Qt
Bash idiom trap for signals; a read loop over a pipe
PowerShell native Register-ObjectEvent, Register-EngineEvent
SQL native triggers on INSERT, UPDATE and DELETE
Regex n/a no events
HTML native element events and on attributes
CSS n/a state pseudo-classes, but no handlers

JavaScript is the language in which event-driven programming is the default. Every host runs scripts as jobs in an event loop, and there is no way to block and wait in the language, so all I/O is done with callbacks, promises or await. C# is the only other core language with events in its syntax. An event member is a list of delegates that only the declaring class can raise, and the C# file of this page shows the compile error when other code tries to raise it.

Python, Java and Kotlin put event loops in the standard library: asyncio and tkinter in Python, the Swing and JavaFX event threads in Java. Go, Rust, C and C++ have no event loop in the standard library. Go does not need one for I/O, because goroutines block cheaply and the runtime uses an event loop of the kernel under them. A for loop over select is still the Go way to react to several sources of events. Rust programs use a channel and an enum of events, or an async runtime from a crate. C and C++ programs use the calls of the operating system directly or through libraries such as libuv, libevent, Boost.Asio and Qt.

SQL triggers and HTML events are event-driven parts of languages that are not general-purpose. A trigger runs when a statement changes a table, and an HTML attribute such as onclick connects a handler to an element.

PythonGitHub
import selectors
import socket

sel = selectors.DefaultSelector()
client, server = socket.socketpair()


def on_server_readable(conn):
    msg = conn.recv(100).decode()
    print("server got", msg)
    conn.send(msg.replace("ping", "pong").encode())


def on_client_readable(conn):
    msg = conn.recv(100).decode()
    print("client got", msg)
    n = int(msg.split()[1])
    if n < 3:
        conn.send(f"ping {n + 1}".encode())
    else:
        sel.unregister(client)
        sel.unregister(server)


sel.register(server, selectors.EVENT_READ, on_server_readable)
sel.register(client, selectors.EVENT_READ, on_client_readable)
client.send(b"ping 1")

while sel.get_map():
    for key, _ in sel.select(timeout=1):
        key.data(key.fileobj)
Output
server got ping 1
client got pong 1
server got ping 2
client got pong 2
server got ping 3
client got pong 3

This code runs but gives a wrong answer on purpose.

import asyncio
import time


async def main():
    loop = asyncio.get_running_loop()
    start = loop.time()
    late = []
    loop.call_later(0.05, lambda: late.append(loop.time() - start - 0.05))
    time.sleep(0.3)  # blocks the whole loop
    await asyncio.sleep(0.1)
    print("timer ran late by more than 0.2 s:", late[0] > 0.2)


asyncio.run(main())
Output
timer ran late by more than 0.2 s: True
  • Verdict: stdlib. The selectors module waits on many sockets at once and is the base of asyncio. The Python documentation says it "allows high-level and efficient I/O multiplexing, built upon the select module primitives." asyncio adds an event loop with timers, callbacks and coroutines, and tkinter has an event loop for user interfaces.
  • In the first block, each handler runs when its socket has data, does a little work and returns to the loop. The data in key.data is the handler that register stored.
  • In the wrong block, time.sleep blocks the thread that runs the loop, so the timer cannot fire on time. Use await asyncio.sleep, or move blocking work to a thread with loop.run_in_executor or asyncio.to_thread.
#include <functional>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <utility>
#include <vector>

class Loop {
public:
    using Handler = std::function<void(const std::string&)>;

    void on(const std::string& name, Handler h) { handlers_[name].push_back(std::move(h)); }
    void post(std::string name, std::string data) { queue_.emplace(std::move(name), std::move(data)); }

    void run() {
        while (!queue_.empty()) {
            auto [name, data] = queue_.front();
            queue_.pop();
            for (auto& h : handlers_[name]) h(data);
        }
    }

private:
    std::map<std::string, std::vector<Handler>> handlers_;
    std::queue<std::pair<std::string, std::string>> queue_;
};

int main() {
    Loop loop;
    loop.on("request", [&](const std::string& path) {
        std::cout << "request " << path << "\n";
        loop.post("response", path == "/" ? "200" : "404");
    });
    loop.on("response", [](const std::string& code) { std::cout << "response " << code << "\n"; });

    loop.post("request", "/");
    loop.post("request", "/missing");
    loop.run();
}
Output
request /
request /missing
response 200
response 404
  • Verdict: idiom. The standard library has no event loop. A queue of events and a map from names to std::function handlers is the basic form. Boost.Asio and the user interface toolkits Qt and wxWidgets give complete event loops, and Qt connects events to handlers with signals and slots.
  • The responses come after both requests, because a handler only posts a new event. It does not call the next handler directly.
JavaGitHub
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.ArrayDeque;
import java.util.Queue;

public class Main {
    static class Thermostat {
        private final PropertyChangeSupport events = new PropertyChangeSupport(this);
        private int target = 20;

        void addListener(PropertyChangeListener listener) {
            events.addPropertyChangeListener(listener);
        }

        void setTarget(int value) {
            int old = target;
            target = value;
            events.firePropertyChange("target", old, value);
        }
    }

    public static void main(String[] args) {
        Queue<Runnable> loop = new ArrayDeque<>();
        Thermostat t = new Thermostat();
        t.addListener(e -> System.out.println(e.getPropertyName() + ": " + e.getOldValue() + " -> " + e.getNewValue()));
        t.addListener(e -> loop.add(() -> System.out.println("later: heater set for " + e.getNewValue())));

        t.setTarget(22);
        t.setTarget(22); // no event: the value did not change
        t.setTarget(18);
        System.out.println("queued: " + loop.size());
        while (!loop.isEmpty()) {
            loop.poll().run();
        }
    }
}
Output
target: 20 -> 22
target: 22 -> 18
queued: 2
later: heater set for 22
later: heater set for 18
  • Verdict: stdlib. Java uses listener interfaces for events. java.beans.PropertyChangeSupport keeps a list of listeners and calls them when a property changes, and it does not fire when the old and new values are equal. Swing and JavaFX run all user interface handlers on one event thread.
  • The second listener does not act at once. It puts a job on a queue, and the loop at the end runs the jobs. This is the split between an event and the work that it causes.
#include <poll.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

static int requests[2], replies[2];
static int done;

static void on_request(int fd)
{
    char buf[64];
    ssize_t n = read(fd, buf, sizeof buf - 1);
    buf[n] = '\0';
    printf("request: %s\n", buf);
    write(replies[1], "ok", 2);
}

static void on_reply(int fd)
{
    char buf[64];
    ssize_t n = read(fd, buf, sizeof buf - 1);
    buf[n] = '\0';
    printf("reply: %s\n", buf);
    done = 1;
}

int main(void)
{
    if (pipe(requests) != 0 || pipe(replies) != 0)
        return 1;
    struct pollfd fds[2] = { { requests[0], POLLIN, 0 }, { replies[0], POLLIN, 0 } };
    void (*handlers[2])(int) = { on_request, on_reply };

    write(requests[1], "GET /", 5);
    while (!done) {
        if (poll(fds, 2, 1000) <= 0)
            return 1;
        for (int i = 0; i < 2; i++)
            if (fds[i].revents & POLLIN)
                handlers[i](fds[i].fd);
    }
    return 0;
}
Output
request: GET /
reply: ok
  • Verdict: idiom. ISO C has no events. On POSIX systems, poll and select wait until one of several file descriptors is ready, and an array of function pointers maps each descriptor to its handler. Linux has epoll, the BSDs and macOS have kqueue, and Windows has I/O completion ports. Libraries such as libuv and libevent wrap them.
var button = new Button();
button.Clicked += (sender, e) => Console.WriteLine($"handler 1: click {e.Count}");
EventHandler<ClickArgs> second = (sender, e) => Console.WriteLine("handler 2");
button.Clicked += second;

button.Click();
button.Clicked -= second;
button.Click();

class ClickArgs(int count) : EventArgs
{
    public int Count => count;
}

class Button
{
    int clicks;
    public event EventHandler<ClickArgs>? Clicked;
    public void Click() => Clicked?.Invoke(this, new ClickArgs(++clicks));
}
Output
handler 1: click 1
handler 2
handler 1: click 2

This code does not compile, on purpose.

var button = new Button();
button.Clicked?.Invoke(button, EventArgs.Empty);

class Button
{
    public event EventHandler? Clicked;
}
  • Verdict: native. The event keyword declares a list of delegates. Code outside the class can only add a handler with += and remove one with -=. Only the class that declares the event can raise it, so the second block fails with error CS0070.
  • Clicked?.Invoke calls nothing when no handler is attached. Windows Forms, WPF and other user interface libraries run an event loop on one thread and raise these events from it.
JavaScriptGitHub
import { EventEmitter } from "node:events";

const door = new EventEmitter();
door.on("open", (who) => console.log(`handler 1: ${who} opened the door`));
door.once("open", () => console.log("handler 2: runs once"));

setTimeout(() => console.log("timer"), 0);
Promise.resolve().then(() => console.log("microtask"));
door.emit("open", "ana");
door.emit("open", "bo");
console.log("end of script, listeners:", door.listenerCount("open"));
Output
handler 1: ana opened the door
handler 2: runs once
handler 1: bo opened the door
end of script, listeners: 1
microtask
timer

This code runs but gives a wrong answer on purpose.

const start = Date.now();
setTimeout(() => console.log("timer late by at least 200 ms:", Date.now() - start >= 250), 50);
while (Date.now() - start < 300) {
  // a long computation in one job
}
Output
timer late by at least 200 ms: true
  • Verdict: native. JavaScript runs in an event loop in every host. Browsers dispatch DOM events to listeners from addEventListener, and Node.js has EventEmitter for events of its own objects.
  • emit calls the listeners at once, in the order they were added. It does not go through the event loop. The promise callback runs as a microtask when the script ends, and the timer runs in a later turn of the loop.
  • In the wrong block, the timer is due after 50 ms, but the loop cannot run it until the current job ends. Split long work into pieces, or move it to a worker.
package main

import "fmt"

type event struct {
	kind string
	data string
}

func main() {
	events := make(chan event)
	done := make(chan struct{})
	handlers := map[string][]func(string){
		"key":    {func(d string) { fmt.Println("key pressed:", d) }},
		"resize": {func(d string) { fmt.Println("window size:", d) }},
	}

	go func() {
		for _, e := range []event{{"key", "a"}, {"resize", "80x24"}, {"key", "q"}} {
			events <- e
		}
		close(done)
	}()

	for {
		select {
		case e := <-events:
			for _, h := range handlers[e.kind] {
				h(e.data)
			}
		case <-done:
			fmt.Println("no more events")
			return
		}
	}
}
Output
key pressed: a
window size: 80x24
key pressed: q
no more events
  • Verdict: idiom. Go has no event loop in the language, because goroutines can block cheaply. A loop over select on several channels is the Go form of an event loop: each case is a source of events, and the body of the case is the handler.
  • The runtime itself is event-driven: when a goroutine waits for the network, the scheduler parks it and uses epoll, kqueue or IOCP to learn when the socket is ready.
RustGitHub
use std::sync::mpsc;
use std::thread;

enum Event {
    Key(char),
    Resize(u16, u16),
    Quit,
}

fn main() {
    let (tx, rx) = mpsc::channel();
    let producer = thread::spawn(move || {
        for e in [Event::Key('a'), Event::Resize(80, 24), Event::Key('q'), Event::Quit] {
            tx.send(e).unwrap();
        }
    });

    let mut typed = String::new();
    for event in rx {
        match event {
            Event::Key(c) => typed.push(c),
            Event::Resize(w, h) => println!("resize to {w}x{h}"),
            Event::Quit => break,
        }
    }
    producer.join().unwrap();
    println!("typed {typed:?}");
}
Output
resize to 80x24
typed "aq"
  • Verdict: idiom. The standard library has channels and threads but no event loop. An enum of events and a match in a loop give a typed dispatch, and the compiler checks that each kind of event has a handler.
  • Async Rust is event-driven under the surface: runtimes such as Tokio poll futures when the operating system reports that a socket or timer is ready. The runtimes are crates, not part of the standard library.
  • Callbacks. A handler passed as a function value is a callback. See higher-order functions and closures.
  • Promises and futures. A promise is an object for a result that an event will deliver later, and handlers attach to it. See futures.
  • Async/await. The compiler turns sequential code into handlers on an event loop. See async/await.
  • Observer pattern. An object keeps a list of listeners and notifies them of changes, as PropertyChangeSupport does in the Java file.
  • Publish and subscribe. Senders publish messages to topics, and a broker delivers them to subscribers. Neither side knows the other.
  • Reactive programming. Streams of events are values that can be mapped, filtered and joined, as in Rx libraries and Kotlin Flow.
  • The actor model. Each actor has a mailbox and handles one message at a time, which is an event loop for each actor. See channels.
  • Interrupts and signals. Hardware interrupts and Unix signals are events at the level of the machine and the operating system. Their handlers can run at almost any point and have strict limits on what they may do.
  • Event sourcing. A system stores the list of events that changed its state, and computes the state by replaying them.

Pitfalls

  • Blocking the loop. A handler that waits for I/O or computes for a long time stops all other events. The wrong blocks in the Python and JavaScript files show a timer that fires late. Use asynchronous calls, split the work, or move it to a thread or a worker.
  • Callback nesting. When each step waits for the last one, callbacks nest deeper and deeper, and error handling repeats at each level. Promises and async/await flatten the code.
  • Lost errors. An exception in a handler goes to the event loop, not to the code that registered the handler. A rejected promise without a handler can be lost. Handle errors in each handler, and install a handler for unhandled rejections.
  • Listener leaks. A listener that is never removed keeps its closure and all that the closure refers to. Remove listeners when the object that registered them goes away. See memory leaks.
  • Order assumptions. Synchronous events, such as emit in Node.js, run the handlers before emit returns. Asynchronous events run later. A program that mixes the two can see events in an order its author did not expect.
  • Reentrancy. A handler that raises an event can cause another handler to change the same state while the first handler is still running.
  • Starvation by microtasks. A microtask that always schedules another microtask stops the loop from reaching timers and I/O.

Cost

An event loop serves many connections with one thread. Each waiting connection costs only its state object and a registration with the kernel, not a thread stack, which is why event-driven servers such as nginx and Node.js handle tens of thousands of connections in little memory. Ousterhout noted that events have "no locking overheads" and "no context switching" on one CPU.1 The calls epoll and kqueue cost time in proportion to the number of ready descriptors, not the number of registered ones. The limit is the CPU: one loop uses one core, so a program runs one loop for each core, or moves CPU-heavy work to other threads. Each event also costs a dispatch: a lookup of the handlers and an indirect call, and for promises an allocation.

History

Event-driven programs began with interrupts in the hardware of the 1950s, which made the processor jump to a handler when a device needed service. Interactive graphics systems of the 1960s and 1970s, and the Smalltalk environment at Xerox PARC, built programs around events from the keyboard and the mouse. The Apple Macintosh in 1984, the X Window System in 1984 and Microsoft Windows in 1985 made an event loop the center of every graphical application. On servers, the BSD select call of 1983 let one process wait for many sockets, and Ousterhout's 1995 talk "Why Threads Are A Bad Idea (for most purposes)" argued that events are better than threads for most programs.1 FreeBSD added kqueue in 2000 and Linux added epoll in 2002. Netscape added JavaScript to its browser in 1995 with event handlers on HTML elements. Node.js brought the browser model to servers in 2009, and promises and async/await changed how programs in JavaScript, C#, Python and Rust write event-driven code in the 2010s.

References

  1. Why Threads Are A Bad Idea (for most purposes), John Ousterhout, 1995, slides 8, 10 and 11
  2. HTML Living Standard, WHATWG, 8.1.7 Event loops
  3. The Node.js Event Loop, Node.js documentation, What is the Event Loop?
  4. JavaScript execution model, MDN Web Docs, Run-to-completion

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/M8ZWG3/text.yaml