Concurrency, Synchronization & Deadlock Questions
Correctness of shared-state coordination between concurrent threads and tasks. Covers mutexes (futex-based and spin-then-sleep), semaphores, condition variables, spinlocks, reader-writer locks, and the producer-consumer pattern; atomic operations, compare-and-swap, lock-free and wait-free structures with the ABA problem and safe memory reclamation; memory ordering, barriers and acquire/release semantics; race conditions, data races, critical sections, time-of-check to time-of-use gaps and read-modify-write hazards; deadlock (the Coffman conditions, lock ordering, prevention and detection), livelock and starvation; priority inversion as a locking hazard and the priority-inheritance fix; designing thread-safe structures such as bounded queues, caches, rate limiters, event buses and work-stealing schedulers, with coarse versus fine-grained and per-key locking; alternatives to locking such as thread confinement, message passing, actors and transactional memory; and diagnosing and testing concurrency bugs (heisenbugs, race detectors, stress and replay, reviewing concurrent code). Excludes a specific language's threading API and memory model, concurrency for throughput and pool tuning, distributed locks and consensus, database isolation levels, RTOS ceiling protocols and schedulability, and interrupt masking between ISRs and main code.
What does lock-free mean? Contrast lock-free with wait-free and obstruction-free guarantees, and explain when the extra complexity is worth it.
Sample Answer
Direct answer
Lock-free means: with any number of threads running, whenever the program runs long enough, at least one thread completes its operation. A stalled or killed thread cannot stop the others, unlike a lock where the holder's delay blocks everyone waiting. It is a guarantee about progress, not about speed: a lock-free structure is not automatically faster than a locked one, and it does not promise that every thread finishes (one thread can lose every race). Wait-free is stronger: every operation by every thread completes in a bounded number of its own steps. Obstruction-free is weaker: a thread is guaranteed to finish only if it runs alone for long enough (the others suspended); two threads can keep undoing each other's work and neither finishes (a livelock: threads active but making no progress). The extra complexity is worth it only when blocking is unacceptable (interrupt or real-time code, an audio or game-loop thread that must not wait on a lower-priority thread), when lock convoying (threads repeatedly queuing for a lock that is usually held when they arrive, so most of them spend their time asleep and being woken in turn instead of working) is measured, or for one hot, simple structure such as a single-producer single-consumer queue (a fixed-size circular queue with exactly one thread adding and one removing, so neither needs a lock) or a counter.
Progress guarantees compared
| Guarantee | Meaning | Can an individual thread starve? | Typical example |
|---|---|---|---|
| Blocking (locks) | Progress depends on the holder running | Yes, and everyone stalls if the holder is delayed | Mutex-protected queue |
| Obstruction-free | Finishes if all other threads pause | Yes; livelock possible under contention | Optimistic schemes that abort a rival's half-finished update and retry, such as some software transactional memory designs (updates applied speculatively and rolled back on conflict); see the two-thread scenario below |
| Lock-free | Some thread always completes | Yes, one thread can lose every race | A compare-and-swap (CAS) retry loop |
| Wait-free | Every thread finishes within a bounded number of steps | No | A single-producer single-consumer ring buffer; an operation compiled to one atomic hardware instruction (verify in the disassembly for your target) |
These definitions follow the standard ones summarised at Wikipedia's "Non-blocking algorithm" page: wait-free means "every operation has a bound on the number of steps", lock-free that "at least one of the threads makes progress", obstruction-free that "a single thread executed in isolation ... for a bounded number of steps will complete its operation".
CAS (compare-and-swap) is an atomic instruction: "if this variable still holds the value I read, replace it with my new value, else tell me the current value". A failed CAS means another thread's CAS succeeded in between, which is exactly why a CAS retry loop is lock-free (somebody progressed) but not wait-free (this thread may lose again and again, with no bound).
Obstruction-free in a two-thread scenario
Suppose an update must claim two cells X and Y, and the rule is: if the other cell is already claimed by someone else, release your own claim and retry. T1 claims X, then T2 claims Y. T1 sees Y taken and releases X; T2 sees X still taken or just released, and releases Y; both retry at the same moment and the pattern repeats. If the two keep running in this lockstep, each undoes the other's progress and neither finishes: a livelock. Run T1 alone for long enough and it claims X, claims Y and finishes, which is exactly the obstruction-free promise. Lock-free designs add a rule such as helping the other thread complete its operation, so at least one of them always finishes.
Worked example: an atomic maximum
#include <atomic>
#include <cstdio>
#include <thread>
#include <vector>
std::atomic<long> maxv{0};
std::atomic<long> attempts{0};
// Lock-free "atomic max": a failed CAS means another thread's CAS succeeded in the meantime.
void update_max(long v) {
long cur = maxv.load(std::memory_order_relaxed);
for (;;) {
attempts.fetch_add(1, std::memory_order_relaxed);
if (v <= cur) return;
if (maxv.compare_exchange_weak(cur, v, std::memory_order_release, std::memory_order_relaxed)) return;
// on failure cur now holds the latest value; loop and retry
}
}
int main() {
std::vector<std::thread> ts;
for (int t = 0; t < 4; t++)
ts.emplace_back([t] { for (long i = 0; i < 100000; i++) update_max(i * 4 + t); });
for (auto& t : ts) t.join();
std::printf("max = %ld (expected %d)\n", maxv.load(), 99999 * 4 + 3);
std::printf("CAS-loop passes >= operations: %s\n", attempts.load() >= 400000 ? "yes" : "no");
}
Built with g++ -std=c++17 -O2 -Wall -Wextra -fsanitize=thread cas.cpp -o cas -pthread (gcc 14, Linux container, ThreadSanitizer clean), 4 threads each offering 100,000 values printed:
max = 399999 (expected 399999)
CAS-loop passes >= operations: yes
If a thread were suspended in the middle of update_max, nothing would be locked: the other three keep finishing. With a mutex, a holder suspended inside the critical section would stall all of them. This loop is lock-free and not wait-free: each failed CAS forces another pass, and the number of passes is not bounded for any one thread.
When the extra complexity is worth it
- Hard bound on blocking: an interrupt handler or real-time thread that must not wait on a lock a lower-priority thread holds (which would be a priority inversion).
- A hot, small structure where profiling shows lock hand-off dominates: counters, flags, single-producer single-consumer queues.
- Avoiding lock hazards such as deadlock, or a holder being descheduled.
It is usually not worth it for general containers. The costs are real: the ABA problem (a CAS succeeds because the value went A, B, A, though the structure changed in between, which breaks pointer-based stacks and queues), safe memory reclamation (you cannot free a node another thread may still be reading; two techniques are hazard pointers, where each reader publishes the node it is about to use so a node is freed only when no reader lists it, and epoch-based reclamation, where a node is freed once every thread has moved past the period in which it could still have seen it), and memory-ordering mistakes that tests rarely catch. Lock-free is also not automatically faster: under heavy contention every CAS retry re-reads a cache line other cores are fighting over.
Recommendation
Use a mutex by default. Use lock-free only for a single simple structure and only after measurement, preferring a well-tested library implementation over writing your own; use wait-free where a bound on every operation is a hard requirement (an ISR producing into a ring buffer for one consumer).
Design a mutex that supports priority inheritance. What state does it keep, how do acquire and release work, and how do you handle nested locks and bound the priority adjustments?
Sample Answer
Direct answer
Priority inheritance fixes priority inversion: a high-priority task H blocks on a mutex held by a low-priority task L, and a medium-priority task M that does not need the mutex keeps pre-empting L, so H effectively waits on M. The fix is that while H is blocked on L's mutex, L runs at H's priority (L inherits it). When L releases the mutex, L drops back to the priority its remaining locks justify, and the mutex goes to the highest-priority waiter. The mutex must therefore remember its owner and its waiters, and each task must remember its base priority, its current effective priority, the mutex it waits on, and the mutexes it holds.
State the design keeps
| Object | Field | Purpose |
|---|---|---|
| Task | base_prio | Priority the task was given. Inheritance never changes it. |
| Task | eff_prio | What the scheduler uses. Always max(base_prio, highest waiter priority on any mutex it holds). |
| Task | blocked_on | The one mutex it waits for. A task waits for at most one thing, so following blocked_on then owner gives a chain, never a tree. |
| Task | held[] | Mutexes it owns, needed to recompute eff_prio on release. |
| Mutex | owner | Who holds it, or none. |
| Mutex | waiters | Tasks blocked on it, picked by priority (a sorted list or heap in a real kernel). |
Convention here: a larger number means a higher priority.
Acquire and release
Acquire (pi_lock). If the mutex is free, take it. Otherwise record blocked_on, add the caller to the waiters, then propagate: set the owner's eff_prio to the caller's if that is higher; if that owner is itself blocked on another mutex, move to that mutex's owner and repeat. Stop when the next owner already has an equal or higher priority, when the owner is not blocked, or when you come back to the caller (a cycle, which is a deadlock: undo the wait and report it).
Release (pi_unlock). Remove the mutex from the owner's held list. Give it to the highest-priority waiter, who becomes the owner and stops being blocked. Then recompute the old owner: max(base_prio, highest waiter on each mutex it still holds). This is the nested-locks rule: a task holding two mutexes must not fall to its base priority when it releases one if a high-priority task still waits on the other.
Bounding the adjustments.
- Each task waits for at most one mutex, so the chain is a simple path and the walk visits each task at most once. Its length is bounded by the number of tasks, and a cycle is detected instead of looped on. The code also has a hard hop limit as a second guard.
- A boost is a copy of an existing priority, never an increase, so no task can exceed the highest priority present.
- Time spent blocked is bounded by the critical sections along the chain, so keep critical sections short and do not call blocking functions while holding a lock.
- Linux's real-time mutex does the same kind of chain walk, and the kernel's rt-mutex design document says that, to prevent denial-of-service attacks, it holds at most two different locks at a time while it walks the chain: it lets go of the earlier locks as it moves along, rather than holding every lock in the chain at once.
Worked example, compiled and run on the host model
This is a model of the kernel-side bookkeeping, with no real scheduler and no real blocking, so every state change can be asserted. It was compiled and run on a Linux container (not on an RTOS or microcontroller): gcc -std=c11 -O1 -Wall -Wextra -Wno-missing-field-initializers -fsanitize=address,undefined pimutex.c -o pi && ./pi. The model has no waiter timeouts and no priority-change calls; a real kernel must re-run the same recompute along the chain on either.
#include <assert.h>
#include <stdio.h>
/* Larger number = higher priority. This models the kernel-side bookkeeping only
(no real scheduler, no real blocking), so every state change can be checked. */
#define MAX_TASKS 8
#define MAX_HELD 4
#define MAX_WAIT 4
typedef struct mutex mutex_t;
typedef struct task {
const char *name;
int base_prio; /* never changed by inheritance */
int eff_prio; /* what the scheduler uses */
mutex_t *blocked_on; /* at most one: a task waits on one mutex at a time */
mutex_t *held[MAX_HELD];
int nheld;
} task_t;
struct mutex {
const char *name;
task_t *owner;
task_t *waiters[MAX_WAIT];
int nwait;
};
static int highest_waiter_prio(const mutex_t *m) {
int p = -1;
for (int i = 0; i < m->nwait; i++) if (m->waiters[i]->eff_prio > p) p = m->waiters[i]->eff_prio;
return p;
}
/* eff = max(base, highest-priority waiter on ANY mutex still held) */
static void recompute(task_t *t) {
int p = t->base_prio;
for (int i = 0; i < t->nheld; i++) {
int w = highest_waiter_prio(t->held[i]);
if (w > p) p = w;
}
t->eff_prio = p;
}
/* Walk owner -> the mutex the owner waits on -> its owner ... raising priorities.
The walk is bounded: it visits each task at most once and stops on a cycle (deadlock). */
static int propagate(task_t *from, int *depth) {
mutex_t *m = from->blocked_on;
int hops = 0;
while (m && m->owner) {
task_t *o = m->owner;
if (o == from) return -1; /* cycle: report deadlock, do not loop */
hops++;
if (hops > MAX_TASKS) return -1; /* defensive hard bound */
if (o->eff_prio >= from->eff_prio) break; /* nothing more to raise down the chain */
o->eff_prio = from->eff_prio;
m = o->blocked_on;
}
*depth = hops;
return 0;
}
/* returns 1 if acquired, 0 if the caller must block, -1 if blocking would deadlock */
static int pi_lock(task_t *t, mutex_t *m) {
if (!m->owner) { m->owner = t; t->held[t->nheld++] = m; return 1; }
t->blocked_on = m;
m->waiters[m->nwait++] = t;
int depth = 0;
if (propagate(t, &depth) < 0) { /* undo and report */
m->nwait--; t->blocked_on = NULL;
/* the failed walk already raised owners along the chain: recompute them, nearest first */
int guard = 0;
for (mutex_t *w = m; w && w->owner && guard < MAX_TASKS; w = w->owner->blocked_on, guard++)
recompute(w->owner);
return -1;
}
return 0;
}
/* returns the new owner (highest-priority waiter) or NULL */
static task_t *pi_unlock(task_t *t, mutex_t *m) {
assert(m->owner == t);
int k = 0; /* drop m from t's held list */
for (int i = 0; i < t->nheld; i++) if (t->held[i] != m) t->held[k++] = t->held[i];
t->nheld = k;
task_t *next = NULL; int bi = -1;
for (int i = 0; i < m->nwait; i++)
if (!next || m->waiters[i]->eff_prio > next->eff_prio) { next = m->waiters[i]; bi = i; }
if (next) {
m->waiters[bi] = m->waiters[--m->nwait];
next->blocked_on = NULL;
m->owner = next; next->held[next->nheld++] = m;
} else m->owner = NULL;
recompute(t); /* deboost: only to what the OTHER held mutexes still justify */
if (next) recompute(next);
return next;
}
#define SHOW(t) printf(" %-4s base=%d eff=%d\n", (t)->name, (t)->base_prio, (t)->eff_prio)
int main(void) {
task_t H = {"H", 30, 30}, M = {"M", 20, 20}, L = {"L", 10, 10};
mutex_t A = {"A"}, B = {"B"};
puts("1) basic inversion: L holds A, H blocks on A");
assert(pi_lock(&L, &A) == 1);
assert(pi_lock(&H, &A) == 0);
SHOW(&L); assert(L.eff_prio == 30); /* M (20) can no longer preempt L */
assert(L.eff_prio > M.base_prio);
puts("2) release restores base priority and hands A to H");
task_t *n = pi_unlock(&L, &A);
assert(n == &H); SHOW(&L); SHOW(&H);
assert(L.eff_prio == 10);
pi_unlock(&H, &A);
puts("3) nested chain: L holds B; M holds A and waits on B; H waits on A");
assert(pi_lock(&L, &B) == 1);
assert(pi_lock(&M, &A) == 1);
assert(pi_lock(&M, &B) == 0); /* M blocked on B, owner L -> L = 20 */
assert(L.eff_prio == 20);
assert(pi_lock(&H, &A) == 0); /* H blocked on A, owner M -> M = 30 -> L = 30 */
SHOW(&M); SHOW(&L);
assert(M.eff_prio == 30 && L.eff_prio == 30);
puts("4) L releases B: L drops to base, M gets B and stays at 30 because H still waits on A");
n = pi_unlock(&L, &B);
assert(n == &M); SHOW(&L); SHOW(&M);
assert(L.eff_prio == 10 && M.eff_prio == 30);
puts("5) multiple held mutexes: deboost only as far as remaining waiters allow");
task_t P = {"P", 5, 5}, Q = {"Q", 15, 15}, R = {"R", 28, 28};
mutex_t C = {"C"}, D = {"D"};
assert(pi_lock(&P, &C) == 1 && pi_lock(&P, &D) == 1);
assert(pi_lock(&Q, &C) == 0); assert(P.eff_prio == 15);
assert(pi_lock(&R, &D) == 0); assert(P.eff_prio == 28);
pi_unlock(&P, &D); SHOW(&P); assert(P.eff_prio == 15); /* Q still waits on C */
pi_unlock(&P, &C); SHOW(&P); assert(P.eff_prio == 5);
puts("6) a lock cycle is detected, not looped on");
task_t U = {"U", 12, 12}, V = {"V", 14, 14};
mutex_t E = {"E"}, F = {"F"};
assert(pi_lock(&U, &E) == 1 && pi_lock(&V, &F) == 1);
assert(pi_lock(&U, &F) == 0);
int r = pi_lock(&V, &E);
printf(" V tries E -> %d (-1 = would deadlock)\n", r);
assert(r == -1);
SHOW(&U); SHOW(&V); /* the failed attempt must leave no boost behind */
assert(U.eff_prio == 12 && V.eff_prio == 14);
puts("all checks passed");
return 0;
}
Output:
1) basic inversion: L holds A, H blocks on A
L base=10 eff=30
2) release restores base priority and hands A to H
L base=10 eff=10
H base=30 eff=30
3) nested chain: L holds B; M holds A and waits on B; H waits on A
M base=20 eff=30
L base=10 eff=30
4) L releases B: L drops to base, M gets B and stays at 30 because H still waits on A
L base=10 eff=10
M base=20 eff=30
5) multiple held mutexes: deboost only as far as remaining waiters allow
P base=5 eff=15
P base=5 eff=5
6) a lock cycle is detected, not looped on
V tries E -> -1 (-1 = would deadlock)
U base=12 eff=12
V base=14 eff=14
all checks passed
Every assert passed. How propagate works, line by line: it starts at the task that just blocked (from) and looks at the mutex it waits on, m. The loop body takes that mutex's owner o; if o is from the chain has come back to the start, which is the cycle, so it returns -1; if o already has equal or higher priority nothing more needs raising, so it breaks; otherwise it copies from's priority into o and moves on to the mutex o itself waits on. hops counts steps and is capped at MAX_TASKS as a second guard. Case 6 in words: U holds E and V holds F. U asks for F and blocks (V already has priority 14 so nothing is raised). V then asks for E: the walk goes to E's owner U, raises U to 14, then to the mutex U waits on, F, whose owner is V, the caller, so it reports the cycle and -1. The failed attempt had raised U, so pi_lock recomputes the owners along the chain before returning, and the printed U and V lines show that no boost was left behind (U back at 12). Case 3 is the nested chain (H waits for M who waits for L, so L reaches 30). Case 4 shows M keeps 30 after receiving B because H still waits on A. Case 5 shows the deboost stops at 15, not at the base 5, while Q still waits on C.
Trade-offs and pitfalls
- Inheritance does not prevent deadlock. The cycle case simply detects it. Preventing it needs a lock ordering rule. A priority ceiling protocol (every mutex has a ceiling equal to its highest-priority user) is the other classic fix: if a mutex is used by tasks at priorities 10 and 30, its ceiling is 30, and any task that locks it runs at 30 for the whole critical section, so no medium-priority task can preempt it, and no waiting is needed to trigger the boost.
- Never lock it from an interrupt handler. An ISR (interrupt service routine, the code the CPU runs when a hardware event fires) is not a schedulable task with a priority to inherit, and it cannot block.
- Cost. Chain walks happen in the slow path (when blocked), and the fast path is one atomic operation. The price is bookkeeping and a longer slow path.
- Pitfall. Forgetting to recompute from the remaining held mutexes on release leaves a task boosted forever, or drops it too early. Case 5 is the test that catches it.
Where operating-system priority inheritance is unavailable or unsuitable, how do you prevent or soften priority inversion? Give application-level design changes and scheduler or deployment options.
Sample Answer
Priority inversion is when a high-priority task is stuck waiting for a lock held by a low-priority task, and a medium-priority task keeps the low one from running. A single-core example with illustrative times: a low task L takes the lock at t = 0 and needs 3 ms of CPU inside it; a high task H wakes at t = 1 ms and blocks on the lock, by which time L has 2 ms of its section left; a medium task M, which does not use the lock, also wakes at t = 1 ms and needs 50 ms of CPU. The scheduler always prefers M over L, so L cannot run until M finishes at t = 51 ms, then finishes its last 2 ms and releases the lock at t = 53 ms. H waited from t = 1 to t = 53, 52 ms (50 ms of M plus 2 ms of L) instead of the 2 ms it would have waited without M, delayed by a task of lower priority than itself.
Priority inheritance (the lock owner runs at the highest priority of the tasks it blocks; in the example L would run at H's priority, finish in 2 ms, and release the lock) fixes priority inversion only when the OS has it, the lock type supports it and the owner can actually run. POSIX makes it an optional feature, so a design cannot assume it exists. When it is missing or does not fit, the goal changes from "boost the owner" to "never let a high-priority path wait on a lock a low-priority path holds".
Recommendation, in order
- Remove the shared lock from the high-priority path. Hand data over by message passing to a single owner thread, or publish immutable snapshots (build a new copy, then swap one pointer atomically, meaning a single indivisible write that readers either see in full or not at all). The high-priority thread then reads without locking and cannot be blocked. This is the strongest fix. I would choose it whenever the shared data is small or read-mostly.
- Shorten and bound the critical section. Inside the lock do only memory operations: no I/O, no allocation, no callbacks, no logging. Copy the data out and work on the copy. This does not stop inversion by itself: it shrinks the owner's part of the wait (the 2 ms in the example) but not a medium task's part (the 50 ms). The blocking time is bounded by the owner's remaining critical section only when nothing of middling priority can preempt the owner, for example together with steps 3 to 5 or when every user of the lock runs in one priority class.
- Use a ceiling or non-preemptible section. Under a priority ceiling (POSIX
PTHREAD_PRIO_PROTECT, also optional), each lock is given a ceiling, the highest priority of any task that will ever use it, and a task owning the lock immediately runs at that ceiling, so no medium task can preempt it (in the example, L would run at H's priority from the moment it took the lock, before H even asks). Inheritance boosts the owner only when a higher task blocks; a ceiling boosts it always. On a single core, a non-preemptible section (a stretch of code during which the scheduler is not allowed to switch tasks) for a few microseconds does the same job crudely. - Use the scheduler and deployment. Run every user of the lock at the same priority class (the scheduler's band of priorities, such as real-time versus normal) so nobody sits between them; pin the lock's users to one core or reserve cores for the high-priority path; guarantee the low-priority work a minimum CPU share so a holder cannot be preempted indefinitely.
- Use a PI-capable lock where one exists. Linux provides priority-inheriting futexes (PI futexes, the kernel's fast user-space locks with inheritance), backed by a kernel real-time mutex (the kernel's built-in inheriting lock; see its documentation), and POSIX exposes inheritance as
PTHREAD_PRIO_INHERIT. Use it for the shared state you cannot eliminate.
Three techniques compared
These are qualitative engineering judgments, not measurements.
| Technique | Implementation cost | Runtime overhead | What it leaves |
|---|---|---|---|
| Shorten the critical section, copy out | Low: local refactor | Tiny: one copy | Still blocked for the remaining section, and a medium task can still preempt the holder |
| Ceiling or preemption-off section | Medium: assign ceilings, review every lock user | Small per lock, but all other tasks wait while a non-preemptible section runs | Blocks tasks that never use the lock if preemption is disabled |
| Message passing or atomic snapshot swap | High: redesign and prove correct | A copy or atomic operations per update | No blocking of the high-priority path |
The mobile version
A background task holds a lock while it writes to a database, and the UI thread (the main thread that must draw every frame) needs the same lock, so the UI freezes. The fix is structural, in the order above: never hold the lock across the slow write (take a snapshot under the lock, write outside it); give the data a single serial owner (a serial queue, which runs submitted tasks one at a time in order, or an actor, an object that processes one message at a time and owns its data) so the UI posts a request and never waits; and show cached data on the UI thread while the update is in flight. Platform priority hints (quality-of-service, QoS, classes on Apple platforms, labels such as user-interactive or background that the system maps to priorities; thread priority on Android) can raise the background thread, but whether a given lock type boosts its holder is platform- and API-specific, so I would not rely on it without reading that API's documentation and measuring. The trade-off for the structural fix is staleness (the UI shows the previous snapshot for a moment) and extra memory for the copy.
What would change my choice: if the shared object is large and writes are frequent, copying becomes expensive and I would move to a ceiling or PI-capable lock with a short critical section.
A privileged agent checks that a user may read a file and then opens it in a separate step. Explain how concurrency lets an attacker exploit the gap, and how you would redesign the access so the check and the use cannot be separated.
Sample Answer
Direct answer
This is a TOCTOU (time-of-check to time-of-use) race: the agent checks something about a path in one step and acts on the path in a second step, and between the two the attacker changes what the path refers to. The attacker needs a concurrent process, which a multi-user machine always provides, and a directory they can write to, in which they replace a file they may read with a symbolic link (a symlink, a file that is just a pointer to another path) to a file they may not read, right after the check passes. The privileged agent then opens the secret with its own privileges. The redesign principle: never check a name and then use the name. Make the check and the use one operation, or check the object you already hold (a file descriptor: the small integer the kernel gives a process when it opens a file, which stands for that one opened file no matter what name it was opened by), or let the kernel do the permission check at open time by running the open with the user's credentials.
The attack in order
- The agent runs with elevated rights (for example a root daemon, or a set-user-ID program: an executable marked so that it runs with its owner's identity rather than the caller's, which is how a normal user can trigger privileged work). A user asks it to read
/srv/pub/report. - Check: the agent decides the request is allowed (the path is inside
/srv/pub, oraccess(), a call that asks whether the real user may read the path, says yes). - The attacker's process, running in a loop, deletes
reportand recreates it as a symlink to/srv/secret/key.txt(and back, to make the check pass on the next try). - Use: the agent calls
open("/srv/pub/report"). If the swap landed between the agent's check and its open, the agent opens the secret and returns it. The attacker does not need to be precise: it loops and retries until the scheduler places the swap in the window, and each try is cheap. The Linux manual page foraccess(2)warns that using it to check authorization beforeopen(2)"creates a security hole" for exactly this reason.
Demonstration (C, Linux container, compiled with GCC 14)
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <linux/openat2.h>
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <unistd.h>
#define BASE "/tmp/toctou-demo" /* the only directory users may read from */
static atomic_int stop;
/* Attacker: flips BASE/report between a plain file and a symlink to the secret. */
static void *attacker(void *arg) {
(void)arg;
char link[256];
snprintf(link, sizeof link, BASE "/pub/report");
while (!atomic_load(&stop)) {
unlink(link); int fd = open(link, O_CREAT | O_WRONLY, 0644); if (fd >= 0) close(fd);
unlink(link); if (symlink(BASE "/secret/key.txt", link) != 0) {}
}
return NULL;
}
/* VULNERABLE: check the path (resolve it, require the BASE/pub prefix), then open the path again. */
static int read_vulnerable(const char *path, char *buf, size_t n) {
char real[4096];
if (!realpath(path, real) || strncmp(real, BASE "/pub/", strlen(BASE "/pub/")) != 0) return -1; /* check */
int fd = open(path, O_RDONLY); /* use */
if (fd < 0) return -1;
ssize_t r = read(fd, buf, n - 1); close(fd);
if (r < 0) return -1;
buf[r] = 0; return 0;
}
/* FIXED: one openat2 call resolves and opens, refusing any symlink or escape from the directory fd. */
static int read_fixed(int dirfd, const char *rel, char *buf, size_t n) {
struct open_how how = { .flags = O_RDONLY, .resolve = RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS };
int fd = syscall(SYS_openat2, dirfd, rel, &how, sizeof how);
if (fd < 0) return -1;
struct stat st;
if (fstat(fd, &st) != 0 || !S_ISREG(st.st_mode)) { close(fd); return -1; } /* checks on the SAME object */
ssize_t r = read(fd, buf, n - 1); close(fd);
if (r < 0) return -1;
buf[r] = 0; return 0;
}
int main(int argc, char **argv) {
int fixed = argc > 1 && !strcmp(argv[1], "fixed");
system("rm -rf " BASE "; mkdir -p " BASE "/pub " BASE "/secret; echo TOP-SECRET > " BASE "/secret/key.txt");
int dirfd = open(BASE "/pub", O_RDONLY | O_DIRECTORY);
pthread_t t; pthread_create(&t, NULL, attacker, NULL);
long leaks = 0, attempts = 0, plain_reads = 0; char buf[64];
for (; attempts < 2000000 && !(leaks && !fixed); attempts++) {
int rc = fixed ? read_fixed(dirfd, "report", buf, sizeof buf)
: read_vulnerable(BASE "/pub/report", buf, sizeof buf);
if (rc == 0 && strncmp(buf, "TOP-SECRET", 10) == 0) leaks++;
else if (rc == 0) plain_reads++;
}
atomic_store(&stop, 1); pthread_join(t, NULL);
printf("%s: secret leaked = %s, ordinary reads served = %s\n", fixed ? "openat2 version" : "check-then-open version",
leaks ? "YES" : "no", plain_reads ? "yes" : "no");
return 0;
}
How to read the program. The attacker thread loops forever: it deletes pub/report, creates it as an ordinary empty file, deletes it again, then recreates it as a symlink to the secret. So at any instant the name report is either an ordinary file (what passes the check) or a symlink to the secret (what the attacker wants opened). In read_vulnerable, the line marked check calls realpath (resolves a path to its final absolute location, following symlinks) and requires the result to start with the pub directory; the line marked use calls open(path), which resolves the name from scratch. If the name is the ordinary file at the check and the symlink at the open, the agent reads the secret. In read_fixed there is only one name lookup, the openat2 call; every later check (fstat) is on the descriptor it returned.
gcc -O2 -pthread toctou.c -o toctou && ./toctou vulnerable && ./toctou fixed printed:
check-then-open version: secret leaked = YES, ordinary reads served = yes
openat2 version: secret leaked = no, ordinary reads served = yes
The vulnerable reader resolves the path with realpath, requires it to stay under pub, then opens the same string again: it leaked the secret in a run capped at 2,000,000 attempts (it stops at the first leak; the number of attempts varies from run to run, so the program prints only yes or no). The fixed reader makes 2,000,000 attempts under the same attacker and never leaked, while still serving ordinary files. (The "ordinary reads served" column confirms the fixed version is not just failing every call.)
The redesign, in order of preference
- Do the open with the user's rights, so the kernel makes the check and the open one atomic step: the effective user ID is the identity the kernel uses for permission checks, so temporarily switch it to the caller's (
seteuid(user_id)), callopenon the requested path, and switch back to the agent's own identity. In a multithreaded agent, open from an unprivileged helper process instead (fork a child, drop its identity to the user's for good, open, and pass the descriptor back over a Unix socket), because switching identity affects every thread of the process. With either, the kernel refuses the open if the user may not read the target, and a symlink swap only reaches files the user could read anyway. Theaccess(2)manual page recommends this approach: it says a safer alternative is to temporarily switch the process's effective user ID to the real ID and then callopen(2). - Open once, then check the file descriptor, not the name: after
open, usefstat(fd)to verify type, owner and mode, then read through that same descriptor. A descriptor refers to one underlying file regardless of what the name later points to. - Constrain the resolution while opening:
openat2(Linux 5.6 and later) relative to a directory descriptor withRESOLVE_BENEATH(refuse any path component that is not a descendant of that directory) andRESOLVE_NO_SYMLINKS(refuse symlinks; it also refuses "magic links", special/procentries that look like symlinks but jump to a file the process has open). The fixed function in the code does this and thenfstats the opened descriptor. On older kernels, walk the path one component at a time withopenatandO_NOFOLLOW(fail if the last component is a symlink). - Remove the writable window: store the agent's files in a directory only the agent can write to, so the attacker cannot swap anything. When the agent must create files, use
O_CREAT | O_EXCL(fail if the name already exists) in a private directory.
What the redesign does not cover
RESOLVE_NO_SYMLINKS stops symlinks, not hard links (a second directory entry for the same file), because a hard link is an ordinary directory entry. If a user can create a hard link to a file inside the allowed directory, the open succeeds, so also check ownership and mode with fstat on the descriptor, or run the open with the user's rights (option 1), which covers every variant.
Pitfalls
Adding a second check right before the use shrinks the window but does not close it. A lock inside the agent does not help, because the attacker is another process and does not take the agent's lock. Checking by path in a program that is meant to be correct under concurrency is the bug, whether the check is access, stat, realpath, or a prefix comparison.
Design a thread-safe ordered set supporting insert, remove, contains and in-order iteration with weakly consistent semantics, plus snapshot views. How do you synchronize it (coarse, fine-grained, optimistic or lock-free), what guarantees does an iterator give while writers run, and how do you reclaim removed nodes safely?
Sample Answer
Direct answer
Recommendation: for a live, in-order set under real contention, use a skip list (a sorted linked list with extra "express" levels, giving expected log n search) built for concurrency, such as Java's ConcurrentSkipListSet: it needs no global lock, its iterators never throw and never miss an element that stays in the set, and the garbage collector reclaims removed nodes. For a snapshot (a frozen point-in-time view), a weakly consistent iterator is not one: keep an immutable sorted structure behind one atomic reference and replace it on each write. If the set is small and rarely written, a single coarse lock is correct and simplest, and you only move up when a profile says it is a bottleneck.
Synchronization options, simplest first
The rows below are the ideas a concurrent skip list is built from; in a garbage-collected language such as Java the library skip list is what you would use rather than building any of them by hand.
| Option | How it works | Cost and limit |
|---|---|---|
| Coarse | One lock around every operation. | Correct and easy. All operations, including reads, serialize. |
| Fine-grained (lock coupling, also called hand over hand) | Hold at most two adjacent node locks and slide forward: lock the next node, then release the previous one, like moving along a rope one hand at a time. | Several threads can be at different places, but every traversal takes a lock per node, so reads still pay. Locks are always taken from head to tail, so there is no deadlock. |
| Optimistic | Traverse with no locks, lock the two nodes you found, then validate they are still linked and adjacent; retry if not. | The traversal takes no locks, but every operation, including contains, must still lock the two nodes it found and validate them, so reads are not lock-free; only the walk is. A node you are standing on may have been removed, so you need safe memory reclamation. |
| Lazy | Add a "deleted" mark to each node: remove marks first (logical delete: the node is still in the list but declared gone) and unlinks second. contains takes no lock. | Fast reads; writers still lock. |
| Lock-free | Update with CAS on pointers (CAS: write a new value only if the current one is still what you last read), with the delete mark stored in the pointer itself (a spare bit of the pointer, so one CAS checks both the link and the mark; Java's AtomicMarkableReference is this pair), and other threads help finish a half-done removal (a thread that meets a marked node while traversing unlinks it itself instead of waiting for the remover). | No locks, hardest to get right, and needs reclamation in non-garbage-collected languages. |
A small trace shows why validation and marking are needed. The list is 1 -> 5 -> 9; one thread inserts 7 while another removes 5. The inserter finds predecessor 5 and successor 9. If the remover unlinks 5 first (1 -> 9), a naive insert would link 7 after the now-detached node 5, and 7 would be lost. In the optimistic design the inserter locks 5 and 9, validates, sees that 5 is marked deleted (or no longer reachable), releases and retries from the head, finds predecessor 1 and successor 9, and produces 1 -> 7 -> 9. In the lock-free design the mark is in 5's next pointer, so the inserter's CAS on that pointer, which expects it unmarked, fails and the insert retries the same way.
A skip list applies the same ideas to a multi-level structure, so searches take expected log n steps instead of linear. The Java documentation for ConcurrentSkipListSet states expected average log(n) cost for contains, add and remove.
What an iterator guarantees while writers run
The java.util.concurrent documentation defines a weakly consistent iterator: it may proceed concurrently with other operations, it never throws ConcurrentModificationException, and it is guaranteed to traverse elements as they existed upon construction exactly once, while it may (but need not) reflect modifications made afterwards. Concretely:
- Ascending order is never violated, and no element is returned twice.
- An element present for the whole scan appears exactly once.
- An element added or removed during the scan may or may not appear.
- It is not a snapshot: if a writer moves a value by removing
athen addingb, a scan can see both, neither, or only one. Example with the set {10, 20, 30} and a writer moving 10 to 25 (remove 10, add 25): a scan that already passed 10 and reaches 25 after the add sees 10 and 25 both. A writer moving 30 to 5 (remove 30, then add 5): a scan that has already passed position 5 before the add and reaches 30 after the removal sees neither 5 nor 30. Invariants spanning several elements, andsize()(not constant time, and inaccurate during modification, per the same documentation), cannot be trusted.
Snapshot views
If a reader needs a consistent point-in-time view (a report, a replica sync), keep the whole set as an immutable value behind one atomic reference. A write copies, modifies the copy, and compare-and-swaps the reference; a snapshot is just reading the reference. Copying the whole set costs O(n) per write, so it only suits small or rarely written sets. For larger sets use a persistent balanced tree (persistent means old versions stay valid after an update), which copies only the O(log n) path (the handful of nodes from the root down to the change, about log base 2 of n of them) and shares the rest with the old version.
Reclaiming removed nodes safely
A reader may be standing on a node a writer just unlinked. Order of events for removal: mark the node deleted, unlink it, and only free it once no reader can still hold it. In a garbage-collected language the collector does that: the node stays alive while any iterator references it, and its next pointer still leads forward, which is why weakly consistent iteration works. In C, C++ or Rust you retire the node and free it later using epoch-based reclamation (free after every thread that could have seen it has passed a quiescent point, a moment at which it holds no pointers into the structure), hazard pointers (readers announce the node they are about to use, and the freer skips announced nodes), or RCU (read-copy-update, a similar grace-period scheme).
Worked example, run in a Linux container
Part one scans a ConcurrentSkipListSet 20,000 times while a writer adds and removes the keys that are not multiples of 10; the 101 keys that are multiples of 10 are never touched, so every scan must find exactly those 101. Part two takes a snapshot of a copy-on-write set, lets four threads add 50 values each, and shows the snapshot unchanged.
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.*;
public class OrderedSet {
// Snapshot-friendly variant: an immutable sorted set behind one atomic reference (copy-on-write).
static final class CowSet {
private final AtomicReference<NavigableSet<Integer>> root =
new AtomicReference<>(Collections.unmodifiableNavigableSet(new TreeSet<>()));
boolean add(int x) {
for (;;) {
NavigableSet<Integer> cur = root.get();
if (cur.contains(x)) return false;
TreeSet<Integer> next = new TreeSet<>(cur); // O(n) copy per write
next.add(x);
if (root.compareAndSet(cur, Collections.unmodifiableNavigableSet(next))) return true;
}
}
NavigableSet<Integer> snapshot() { return root.get(); } // O(1), immutable, never changes
}
public static void main(String[] args) throws Exception {
// Part 1: ConcurrentSkipListSet. Stable keys 0,10,20,... are never removed; keys in between churn.
ConcurrentSkipListSet<Integer> set = new ConcurrentSkipListSet<>();
for (int i = 0; i <= 1000; i += 10) set.add(i);
AtomicBoolean stop = new AtomicBoolean();
Thread writer = new Thread(() -> {
Random r = new Random(42);
while (!stop.get()) {
int k = r.nextInt(1000);
if (k % 10 == 0) continue; // never touch the stable keys
if (r.nextBoolean()) set.add(k); else set.remove(k);
}
});
writer.start();
int scans = 0, outOfOrder = 0, missingStable = 0, dupes = 0;
for (int s = 0; s < 20000; s++) {
int prev = -1, stableSeen = 0;
for (int k : set) { // iterates while the writer runs
if (k <= prev) { if (k == prev) dupes++; else outOfOrder++; }
prev = k;
if (k % 10 == 0) stableSeen++;
}
if (stableSeen != 101) missingStable++;
scans++;
}
stop.set(true); writer.join();
System.out.println("scans=" + scans + " out-of-order=" + outOfOrder + " duplicates=" + dupes
+ " scans-missing-a-stable-key=" + missingStable + " (no ConcurrentModificationException thrown)");
// Part 2: snapshot stays frozen while writers run.
CowSet cow = new CowSet();
for (int i = 0; i < 5; i++) cow.add(i);
NavigableSet<Integer> snap = cow.snapshot();
ExecutorService pool = Executors.newFixedThreadPool(4);
for (int t = 0; t < 4; t++) { final int base = 100 * (t + 1);
pool.submit(() -> { for (int i = 0; i < 50; i++) cow.add(base + i); }); }
pool.shutdown(); pool.awaitTermination(30, TimeUnit.SECONDS);
System.out.println("snapshot=" + snap + " live-size=" + cow.snapshot().size());
}
}
Run with docker run --rm -v "$PWD":/w -w /w eclipse-temurin:21-jdk java OrderedSet.java:
scans=20000 out-of-order=0 duplicates=0 scans-missing-a-stable-key=0 (no ConcurrentModificationException thrown)
snapshot=[0, 1, 2, 3, 4] live-size=205
No scan went out of order, saw a duplicate, or missed a stable key, and no exception was thrown. This supports the documented guarantee for these runs; it is a stress check, not a proof. The snapshot stayed [0, 1, 2, 3, 4] while the live set grew to 205 (5 initial plus 4 x 50).
Trade-offs and pitfalls
- A skip list uses more memory per element than a balanced tree and has worse cache behaviour; a coarse-locked tree beats it for small sets and for single-threaded use.
- Do not use
size()as a decision input under concurrency; track a count separately, or tolerate approximation. - Do not hold a weakly consistent iterator and assume the set did not change between
hasNext()andnext(). ConcurrentSkipListSetrejectsnullelements, because the documentation notes anullcannot be told apart from absence.
Unlock Full Question Bank
Get access to all 13 Concurrency, Synchronization & Deadlock interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.