liveBook · Manning

Callback

As explained in Grokking Concurrency

A callback is a function supplied to another component to be invoked later in response to a specified event or completion condition.

Imagine asking a pizza shop to call when an operator is free. You can do something else instead of waiting on the phone. In an event-driven program, a callback plays the same role: it is a function supplied in advance to run when a specified event occurs. section 11.2

Callbacks need something to notice events and call the right function. An event loop waits for events, matches each one to a registered callback, runs it, then returns to waiting. In a simple Python example, one event can even register another event for the loop to handle later. section 11.3

A server that answers when sockets are ready

A single-threaded pizza server assigns separate callbacks to accepting a connection, reading a message, and writing a reply: _on_accept(), _on_read(), and _on_write(). It registers sockets and their expected events with an event loop. The loop waits in select until a socket is ready, calls its matching callback, and regains control when that callback finishes. This combination of nonblocking I/O, I/O multiplexing, and event-specific handlers is the reactor pattern. section 11.5 section 11.6

The trade-off is control flow. Work that once read as a sequence may be scattered across callbacks; nested chains can become hard to follow or debug. A callback that blocks also stops a single-threaded event loop from serving other events. Callbacks can provide results from asynchronous work, but they are one option, not the only one. section 11.2 section 12.1 section 11.7

How Grokking Concurrency covers it

How deep it goes
Defines callbacks, traces their registration and invocation, and develops socket handlers in a single-threaded server.
Examples
Uses a phone callback, a Python event loop with chained events, and a pizza server with accept, read, and write handlers.
What it assumes
Introduces callbacks through a familiar analogy before showing Python event-loop and socket examples.
What you can do after
Build it from scratch: register event-specific Python callbacks and use them to handle multiple socket clients in one thread.
How it connects
Connects callbacks to event loops, event queues, I/O multiplexing, nonblocking I/O, the reactor pattern, and asynchronous communication.

Also explained in

Compare how 19 books explain callback →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Concurrency. The section links point to the parts of the book it draws on.