Definition
Reentrancy is the property of a function, or of a larger component, that a new call may begin while an earlier call has not yet returned, and both calls still behave correctly. The new call can come on the same thread (one sequence of executing instructions) through recursion, a callback §14.22 (a function handed to other code to call later) or an interrupt handler §6.12, or from another thread. A reentrant function keeps each call’s working state separate, or keeps shared state consistent wherever a new call can begin.
The idea
An interpreter §2.13 is a program that runs another program one instruction at a time. Suppose an interpreter keeps the registers of the program it runs, the small set of numbered variables that the program’s instructions work on, in one global array §14.5. While running a program, the interpreter calls a helper, a function that does part of its work, and the helper calls a callback that the application registered earlier. The callback, written by someone else, runs a second program through the same interpreter. The second run overwrites the global array and returns. When the first run resumes, its registers hold the second program’s values. No second processor and no second thread were involved: one thread entered the interpreter twice, and the second entry overwrote the state of the first.
The picture is a clerk doing a sum on a sheet of paper. Halfway through, the telephone rings, and the caller wants another sum at once. If the clerk works the second sum on the same sheet, the first is ruined. If the clerk takes a fresh sheet for the second sum and returns to the first sheet afterwards, both sums are right. Reentrancy is the fresh-sheet discipline. The picture stops at one point. A clerk can finish the current line before answering the telephone, whereas code is suspended wherever the nested call begins, which for an interrupt §6.11 can be any instruction, and gets no chance to tidy up first. Any state that the nested call can see must therefore already be consistent at every point where a nested call can start.
How it works
A new call reaches a function that is already running by four routes.
Recursion: the function calls itself, directly or through other functions.
Callbacks and hooks: the function calls code it does not control, such as a callback, a logging hook (a function called to record events) or an error handler, and that code calls the function again. This route is the easiest to miss, because the function’s own text contains no call to itself.
Asynchronous interruption: an interrupt handler, which the processor runs when a hardware event arrives, or a signal handler, which the operating system runs when it delivers a signal (a notification such as a timer expiry) to a process, stops the function part-way and calls it.
Other threads: a second thread calls the function while the first is inside it.
The first three routes share one shape: the nested call runs to completion before the interrupted call continues, so calls nest like plates on a pile, where the last plate put on is the first taken off. With threads, the steps of two calls can interleave in any order, and on several processors they run at the same time.
A function is reentrant for the first three routes when four conditions hold.
Private working state. Every value that one call writes and later reads lives in that call’s local variables, which sit on the stack (the memory region that gives each active call its own area), or in a context object that the caller supplies. It does not live in static storage §4.11, variables that exist once for the whole program.
Consistent shared state at every re-entry point. If the function updates shared state, the condition that the rest of the program relies on holds at every point where a nested call can begin. After any such point, the function reads shared state again instead of trusting values it read before.
Reentrant callees. Every function it calls is itself reentrant for the same routes.
No self-blocking lock. It does not hold a lock that a nested call would try to take.
A function that cannot meet these conditions can refuse re-entry instead. A depth counter, incremented on entry and decremented on exit, lets a nested call see that an earlier call is active and return an error before it touches any shared state. Refusal is a sound design if the error reaches the caller and is documented. Against other threads, the counter must be updated with an atomic operation §9.8, an operation that no other thread can observe half done.
Reentrancy and thread safety are different properties, and neither implies the other. A function is thread-safe when calls from several threads at the same time behave correctly.
Thread-safe but not reentrant. A memory allocator that protects its internal lists with a mutex §9.5, a lock that one thread at a time can hold, is thread-safe. If a signal handler calls the allocator while the interrupted thread holds that mutex, the handler waits for a mutex that only the interrupted thread can release, and that thread cannot run until the handler returns: a deadlock §9.14. For this reason POSIX (Portable Operating System Interface), the standard for Unix-like systems, does not list
mallocorprintfamong the functions that are safe to call from a signal handler.Reentrant but not thread-safe. A function that uses one global scratch variable, but saves the variable’s old value on entry and restores it before returning, survives nested calls on one thread, because each nested call finishes and restores the value before the outer call continues. Two threads running the function at the same time can still interleave and corrupt the variable.
Worked example
Take the interpreter from the idea, with real values. Its static array regs holds the registers. The program of the first call sets register 0 to 7, calls a helper, and then adds 1 to register 0.
Call A starts and sets
regs[0]to 7.Call A reaches an instruction that calls a helper, and the helper calls the application’s callback.
The callback starts call B of the same interpreter for a different program. Call B sets
regs[0]to 100, finishes, and returns. The callback and the helper return in turn, and call A continues.Call A executes its next instruction, register 0 plus 1. It reads
regs[0], finds 100, and computes . The intended result was .
Repair by private state. Each call keeps its registers in its own context object, a structure among its local variables on the stack. Call A’s register 0 holds 7, and call B’s register 0 holds 100. After B returns, A reads its own 7 and computes . B’s value of 100 was never at risk either.
Repair by refusal. A static counter depth starts at 0. Call A increments it to 1. Call B finds that depth is 1, not 0, returns the error “busy” without touching regs, and the callback passes that error on. Call A then reads 7, computes 8, and decrements depth to 0 on exit.
Stated precisely
Let be a function and let be a set of routes by which a new call can begin, such as callbacks and interrupt handlers. Call reentrant with respect to if, in every execution in which a call begins through a route in while an earlier call has begun and not returned, each of and returns the result and leaves the effects that the specification of requires for its own inputs.
For the nested routes (recursion, callbacks and hooks, interrupt and signal handlers), the four conditions above are sufficient: private working state, consistent shared state at every re-entry point, reentrant callees, and no self-blocking lock. For the thread route they are not sufficient, because two calls interleave instead of nesting, and every access to shared state also needs synchronization, for example a mutex or atomic operations. A claim of reentrancy means something only when is named.
Limits and common mistakes
Thread-local storage, a separate copy of a variable for each thread, does not fix nested calls on one thread: both calls are on the same thread and see the same copy.
A recursive mutex, a lock that the thread already holding it may take again, avoids the deadlock of the allocator example but allows silent corruption instead: the nested call enters while the outer call may have left shared state half updated.
Signal and interrupt handlers face stricter rules than reentrancy alone. A signal handler may call only async-signal-safe functions, the functions that POSIX lists by name as safe to call from a signal handler (write and _exit are on the list), and an interrupt handler must never wait for a lock or for a slow device.
Private state on the stack costs stack space at every nesting level. Unbounded recursion or re-entry can therefore cause a stack overflow §4.10, so a limit on depth is still needed.
Terminology varies. Some library documentation, such as that of the Qt framework, calls a function reentrant when several threads may call it at the same time provided each call works on different data, which is a narrower, thread-oriented meaning. State which meaning is used.
Reentrancy is also a security problem. In 2016 an attacker drained funds from The DAO [300], a smart contract (a program stored and run on a blockchain) on the Ethereum network; its name comes from the term decentralized autonomous organization. The contract sent a payment before recording the withdrawal, and the receiving code called the withdrawal function again during the payment. The standard defense, update the state before calling out, is the consistent-shared-state condition above.
Questions answered
Can a helper trigger a callback that reenters the same evaluator?
Yes, a helper can trigger a callback that reenters the same evaluator whenever the helper can run code that the evaluator does not control. Here the evaluator is an interpreter that runs a program, and a helper is a function the evaluator calls to do part of its work. If a helper runs an application callback, a logging hook, an error handler, or code that an interrupt starts, that code can call the evaluator again before the first call has returned. The nested call runs on the same thread and finishes before the outer call resumes, so locks do not help. An ordinary lock deadlocks, because the nested call waits for a lock that only the suspended outer call can release. A lock that the same thread may take again lets the nested call in while the outer call’s state is half updated.
The evaluator must therefore choose one of two designs and enforce it. Either it supports re-entry: every call keeps its registers, its program position and its other working state in its own context, and shared state such as caches or counters is consistent at every helper call. Or it refuses re-entry: a depth counter set on entry makes a nested call fail with an error before it touches any state. To learn which routes exist, trace every function the helpers can reach, not only direct calls from the evaluator to itself.
Related entries: Static, stack, and heap storage (§4.11), Mutex (§9.5), Deadlock (§9.14), Callback (§14.22), Interrupt service routine (ISR) (§6.12), Stack overflow (§4.10), Interpreter (§2.13). Further reading: [300].