Definition
A callback is a function that one part of a program hands to another part, which calls it later, when a stated event happens or a stated point in its work is reached. The part that hands over the function registers it; the part that calls the function is the caller, often a library or framework. In C a callback is passed as a function pointer, a variable that holds a function’s address. The callback’s type does not say when, on which thread or under which conditions it will run.
The idea
A radio driver receives packets, and an application wants to act on each one. The driver was written before the application existed, so the driver cannot call the application’s functions by name. Instead, the application hands the driver one of its functions, and the driver calls that function for each packet. Control is inverted: the driver calls the application, not the other way round.
The price is that the callback runs inside the caller’s work and under the caller’s conditions, and the callback’s type, say a function that takes a pointer and a length, shows none of them. The driver may call the callback from an interrupt service routine §6.12 (ISR), the routine the processor runs when a device raises an interrupt §6.11, a hardware signal that suspends the running code; an ISR must not wait. The driver may hold a lock during the call: a variable that lets only one thread at a time use some shared data, where a thread is one sequence of instructions that the operating system schedules. The driver may reuse the packet buffer as soon as the callback returns. And the driver may call the callback before or after sending its own reply, which decides whether the callback can still stop that reply.
How it works
A callback passes through three stages.
Registration. The registering code passes the function to the caller, often with a context pointer to the registering code’s own data, and the caller stores both.
Invocation. When the event happens, the caller calls the stored function with the event’s data and the context pointer.
Return. The callback returns. The caller may ignore the return value, or use it to decide what to do next, for example whether to go on with an operation.
Unregistration removes the function again. A sound interface promises that once unregistration returns, no call to the function is in progress and none will start. Without that promise a call may still be running on another thread, and freeing the context data at that point causes a use-after-free §4.6.
A synchronous callback is called on the same thread before the function that received it returns; the comparison function passed to the C library’s sorting routine qsort is one. An asynchronous callback is called later, after registration has returned, from wherever the caller handles its events: a worker thread that runs queued jobs, an event loop §14.23, which waits for events and runs the handler for each, or an interrupt service routine. An operation that reports its end through such a callback follows the asynchronous completion §9.28 pattern.
Five facts decide what a callback may safely do.
Context: the thread the callback runs on, or interrupt context, meaning inside an ISR. In interrupt context, and in some threads, the callback must not wait for anything, such as a lock, a timer or input.
Locks held: the locks the caller holds during the call. If the callback tries to take one of those locks, or calls a function of the caller that takes one, it can deadlock §9.14: its thread waits forever for a lock that the same thread holds.
Ordering: which effects the caller performs before the call and which after. Only a callback that is called before an effect, and whose return value the caller checks before performing that effect, can prevent the effect.
Argument lifetime: how long the objects that pointer arguments point to stay valid. Usually each pointer is a borrowed pointer §4.3, valid only until the callback returns.
Reentrancy §9.27: whether a new call to the callback can start before an earlier call has returned, from another thread or from inside the earlier call.
Where the caller’s documentation does not state these facts, they come from the caller’s code. Find every place where the stored function is called, and at each one record the thread or interrupt context, the locks held, the effects already performed and still to come, and the lifetime of each argument. A callback called from several places must satisfy the strictest of them.
Worked example
A borrowed buffer. A receive callback gets a pointer to a 3-byte buffer holding the values 10, 20 and 30, valid until the callback returns. The callback puts the pointer on a queue for a worker thread and returns. The driver then reuses the buffer for the next packet, which holds 99, 20 and 30. When the worker later reads the buffer, it sees 99 where the first packet had 10. Had the driver freed the buffer instead, the worker would read freed memory, a use-after-free. The repair copies the 3 bytes, before returning, into memory that the job owns; the worker then reads 10, 20 and 30 whatever the driver does next.
A held lock. A framework holds its lock while it calls each registered callback. is a mutex §9.5 (mutual exclusion lock) that is not recursive: a thread that holds and asks for it again waits. One callback decides to unregister itself and calls the framework’s unregister function, which first takes . The thread already holds , so unregister waits for to be released; is released only after the callback returns; and the callback is waiting for unregister. The thread waits for itself forever. Either the framework releases before calling callbacks, or the callback only records that it wants to be removed and the framework removes it after the call.
Ordering. A framework that calls a policy callback for an outgoing message, checks the return value, and sends the message only if the value is accept, lets the callback stop the message. A framework that sends the message and then calls a logging callback of the same type gives that callback no such power: the message has left before the callback runs. The two callbacks have identical types; only the caller’s order of operations differs. This is the difference between observation and enforcement §1.20.
Stated precisely
The contract between a caller and a callback consists of these facts.
Trigger: the events at which calls , and whether may call more than once per event, not at all (for example after a cancellation §9.29), or after unregistration has returned.
Context: the thread or interrupt context of each call, and whether may wait there.
Locks: the set of locks holds during each call.
Arguments: for each pointer argument, the time interval during which the object it points to stays valid and unchanged, and who may free that object.
Ordering and return value: which effects of happen before the call and which after, and what does with each possible return value, including an error.
Concurrency §9.1: whether two calls of can overlap.
is correct for that contract when four conditions hold. First, performs only actions allowed in its context; in particular it does not wait where waiting is forbidden. Second, takes no lock that holds during the call and calls no function of that takes one; and if takes another lock , no code anywhere waits for one of ’s locks while holding , since otherwise two threads can each wait for the lock the other holds. Third, , and every job starts, uses each argument only within that argument’s validity interval. Fourth, keeps its own shared data consistent when calls overlap. Separately, can prevent an effect of only if calls before , checks the return value, and every route to passes that check.
Limits and common mistakes
A callback’s name and type say nothing about its context, locks, ordering or argument lifetimes. Those facts belong to the caller, and they can change when the caller changes even though the callback’s type stays the same.
Long work in a callback delays the caller. While one callback runs, every other event of an event loop waits, and a long interrupt service routine delays every interrupt of lower priority and every thread. The usual pattern copies what is needed and hands the long work to a thread.
A callback can call back into the caller: it calls a framework function that calls the callback again, or it changes the list of callbacks while the framework is walking that list. A framework that allows this must say so.
Copying an argument fixes its lifetime and nothing else. The copied bytes are as untrusted as the originals and need every check the originals needed.
What the caller does when the callback fails, or when no callback is registered, matters as much as the callback. A caller that treats either case as accept is fail-open §1.14: a failure lets the action proceed.
A callback that holds a lock in a low-priority thread can hold up a high-priority thread that needs the same lock, and medium-priority threads that take the processor from the callback make the wait longer. This is priority inversion §9.16.
Questions answered
On which thread, under which locks, and before which side effects is it called?
A callback, a function that one component hands to another to be called later, runs on whatever thread, under whatever locks and at whatever point relative to side effects the calling code chooses; the callback’s own name and type reveal none of the three. The answer comes from the caller’s documented contract or, where the documentation is silent, from the caller’s code: find every place the stored function is called, and at each one record three facts.
Thread: a synchronous callback runs on the thread that called the registering function, before that function returns. An asynchronous callback runs later, on a worker thread, in an event loop or in an interrupt service routine (ISR); inside an ISR it must not wait.
Locks: the locks held at the call. The callback must not take them again, nor call functions of the caller that take them, or the thread deadlocks.
Side effects: which effects the caller has already performed and which it performs after the call, and whether it checks the callback’s return value before those later effects.
Then check the callback against those facts. It must not wait where waiting is forbidden, must not take a lock already held, and must use pointer arguments only while they stay valid. It can prevent an effect only if it is called before that effect and the caller acts on its return value.
Related entries: Reentrancy (§9.27), Asynchronous completion (§9.28), Observation versus enforcement (§1.20), Event loop (§14.23).