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.
A low-priority task L holds a mutex, a high-priority task H blocks on it, and a medium-priority task M becomes ready. Walk through exactly what runs and when. Show how inheritance changes the timeline and what conditions limit its benefit.
Sample Answer
Priority inversion is a high-priority task being delayed by lower-priority work. Setup: preemptive fixed-priority scheduling on one CPU (a ready task, one that wants the CPU and is not waiting on anything, with the highest priority always runs, and it interrupts a lower-priority task mid-run). Priorities are H > M > L; in the numbers below L = 1, M = 2, H = 3, and a bigger number wins. A task is blocked when it is waiting for something, here a mutex, and so is not ready. Response time is the time from a task's arrival to its completion. A mutex is a lock with an owner; priority inheritance is the rule that a lock owner temporarily runs at the highest priority among the tasks it blocks.
The scenario in numbers (1 tick = 1 ms)
Convention used throughout: tick k is the millisecond from t = k to t = k + 1, so a task that "runs ticks 3 to 7" occupies the CPU from t = 3 until t = 8 and "finishes at t = 8". In the program output below, "released" means the moment the task arrived; it has nothing to do with unlocking the mutex.
- L arrives at 0: 1 ms of work, takes the mutex, 3 ms inside the critical section, unlocks, 1 ms more.
- H arrives at 2: 1 ms of work, locks the mutex, 1 ms in the critical section, unlocks, 1 ms more.
- M arrives at 3: 5 ms of work, never touches the mutex.
A Python simulation (a preemptive fixed-priority loop with one mutex) models it. Its code is below, and its output is the timeline, where each character is one millisecond:
# Preemptive fixed-priority scheduling, one CPU, one mutex, 1 tick = 1 ms.
# A bigger number is a higher priority. Program steps: ("w", ms) work, ("lock",), ("unlock",).
def simulate(inherit):
tasks = {
"L": dict(arrive=0, prio=1, prog=[["w", 1], ["lock"], ["w", 3], ["unlock"], ["w", 1]]),
"H": dict(arrive=2, prio=3, prog=[["w", 1], ["lock"], ["w", 1], ["unlock"], ["w", 1]]),
"M": dict(arrive=3, prio=2, prog=[["w", 5]]),
}
owner, waiting, timeline, finish = None, [], "", {}
def eff(name): # effective priority
p = tasks[name]["prio"]
if inherit and owner == name and waiting:
p = max([p] + [tasks[w]["prio"] for w in waiting])
return p
def ready():
return [n for n, t in tasks.items() if t["arrive"] <= now and t["prog"] and n not in waiting]
for now in range(40):
while ready(): # settle zero-time lock and unlock steps
n = max(ready(), key=eff)
step = tasks[n]["prog"][0]
if step[0] == "lock":
if owner is None:
owner = n; tasks[n]["prog"].pop(0)
else:
waiting.append(n) # blocked: not ready until the owner unlocks
elif step[0] == "unlock":
tasks[n]["prog"].pop(0); owner = None
if waiting: # hand the mutex to the highest-priority waiter
w = max(waiting, key=lambda x: tasks[x]["prio"])
waiting.remove(w); owner = w; tasks[w]["prog"].pop(0)
else:
break
if not ready():
break
n = max(ready(), key=eff)
tasks[n]["prog"][0][1] -= 1
timeline += n
if tasks[n]["prog"][0][1] == 0:
tasks[n]["prog"].pop(0)
if not tasks[n]["prog"]:
finish[n] = now + 1
return timeline, finish
for inherit in (False, True):
line, fin = simulate(inherit)
print("inheritance" if inherit else "no inheritance")
print(" tick :", "".join(str(i % 10) for i in range(len(line))))
print(" running :", line)
print(f" H finished at t = {fin['H']} ms; H released at 2 ms, so response time {fin['H'] - 2} ms; "
f"M finished at {fin['M']}; L finished at {fin['L']}")
Run in a python:3.12-slim container it prints:
no inheritance
tick : 0123456789012
running : LLHMMMMMLLHHL
H finished at t = 12 ms; H released at 2 ms, so response time 10 ms; M finished at 8; L finished at 13
inheritance
tick : 0123456789012
running : LLHLLHHMMMMML
H finished at t = 7 ms; H released at 2 ms, so response time 5 ms; M finished at 12; L finished at 13
Without inheritance. L runs tick 0 and locks the mutex at t = 1; its 3 ms critical section would fill ticks 1 to 3 if nothing interrupted it, but H and M do interrupt it, so L gets only tick 1 of it now and the other 2 ms later. H arrives at t = 2 and preempts L (L holds the lock but is only "ready"), so H runs tick 2, which is its 1 ms of work before the lock. At t = 3 H tries to lock the mutex and blocks, because L owns it. The CPU now has two ready tasks, L (priority 1, still owing 2 ms of critical section) and M (priority 2, just arrived). M wins and runs ticks 3 to 7 (5 ms, finishing at t = 8). Only then does L get the CPU, runs ticks 8 and 9 to finish its critical section, and unlocks at t = 10. H gets the mutex and runs ticks 10 and 11 (1 ms in the critical section, 1 ms more) and finishes at t = 12, which is a response time of 12 - 2 = 10 ms. H was blocked from t = 3 to t = 10, 7 ms, for a lock whose critical section is 3 ms long, because M, which does not even use the lock, sat in between. That is the inversion: H, the highest priority, could not run because of L, and L could not run because of M, so M, the middle priority, effectively outranked H.
With inheritance. At t = 3 H blocks on a mutex owned by L, so L runs at H's priority (3). L now beats M and runs its remaining 2 ms (ticks 3 and 4), unlocks at t = 5, and the mutex goes straight to H, which runs ticks 5 and 6 and finishes at t = 7. L drops back to its own priority at the unlock. M runs afterwards (ticks 7 to 11, finishing at t = 12), and L finishes its last millisecond at t = 13. H's response time falls from 10 ms to 7 - 2 = 5 ms, and the blocking time (t = 3 to t = 5) is exactly L's remaining critical section (2 ms), not M's 5 ms. The price is paid by M, which now finishes at 12 ms instead of 8.
What limits the benefit
- H still waits for the critical section. Inheritance bounds the delay at the owner's remaining critical-section length; it does not remove it. Long sections mean long blocking.
- It needs an owner. A semaphore that any task may release has no owner to boost, so inheritance generally needs a mutex type that records its owner; check what your RTOS does for its semaphores before using one as a lock.
- Chains. If L is itself blocked on a second lock held by a lower task, the boost must propagate. POSIX specifies that inheritance applies recursively to other mutex owners, so a conforming implementation must propagate the boost along the chain.
- It is optional and per-lock. POSIX makes
PTHREAD_PRIO_INHERITan option, and you must request it per mutex (the default isPTHREAD_PRIO_NONE). A lock without the attribute has no protection. - The owner must be runnable. If L is blocked on I/O or a resource that does not propagate priority, boosting L helps nothing.
- Not a deadlock cure, and it adds cost. It adds work on the contended lock and unlock path, and multiple locks can still produce chains of blocking.
I would verify an implementation by running exactly this task set on the target RTOS with and without the attribute and measuring H's worst response time.
What is the difference between a race condition and a data race? Give a small example of each, and explain why code can be free of data races and still contain a race condition.
Sample Answer
Direct answer
A data race is a memory-level fact: two threads access the same memory location at the same time with no ordering between them, at least one access is a write, and the accesses are not both atomic (an atomic access is one the language guarantees happens as a single indivisible step that other threads see either completely or not at all, such as a C11 atomic_int operation; a plain int access is not). In C and C++ the language definition makes the whole program's behaviour undefined if one occurs. A race condition is a logic-level fact: the program's correctness depends on the timing or interleaving of operations, so some interleavings produce a wrong result. A program can have either without the other: you can lock every single access (no data race) and still check a balance in one critical section and withdraw in another (race condition).
The precise definitions
In plain words for the next paragraph: an evaluation is one execution of an expression, such as a read or a write of a variable; a memory location is a variable (or a distinct piece of one) that has its own address; and undefined behaviour means the language places no limit on what the program does. cppreference's statement of the C++ memory model says two evaluations conflict if one modifies a memory location and the other reads or modifies the same location, and a program with two conflicting evaluations has a data race unless both run on the same thread (or in the same signal handler), both are atomic operations, or one happens-before the other. It also says: "If a data race occurs, the behavior of the program is undefined." (Happens-before is the ordering a mutex unlock/lock pair, a thread join, or an atomic release/acquire pair gives you: everything before the unlock is visible after the matching lock.)
| Data race | Race condition | |
|---|---|---|
| Level | Memory accesses (language rule) | Program logic (an invariant about outcomes) |
| Definition | Conflicting accesses, no happens-before, not both atomic | Outcome depends on timing of operations |
| Consequence in C/C++ | Undefined behaviour (compiler may assume it never happens) | A wrong but well-defined result |
| Found by | Race detectors such as ThreadSanitizer (TSan) | Reasoning about invariants, stress tests, review |
| Fixed by | Making accesses atomic or ordering them with a lock | Making the check and the act one atomic step |
Worked example: both bugs in one program, run in a Linux container
One file, two parts. Part 1 is a data race (two threads increment a plain int). Part 2 is a race condition with no data race: every access to balance is under a mutex, but the check and the withdrawal are separate critical sections. A barrier forces both threads to finish their check before either acts, so the bad interleaving happens on every run instead of rarely.
#include <pthread.h>
#include <stdio.h>
/* Part 1: a data race. Two threads write the same int with no synchronization. */
static int hits = 0;
static void *bump(void *arg) { (void)arg; for (int i = 0; i < 100000; i++) hits++; return NULL; }
/* Part 2: a race CONDITION with no data race. Every access is under the mutex,
but check and act are in separate critical sections. */
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static pthread_barrier_t both_checked;
static int balance = 100;
static int withdraw(int amt) {
pthread_mutex_lock(&m);
int ok = balance >= amt; /* check */
pthread_mutex_unlock(&m);
pthread_barrier_wait(&both_checked); /* force the bad interleaving for the demo */
if (!ok) return 0;
pthread_mutex_lock(&m);
balance -= amt; /* act on a stale check */
pthread_mutex_unlock(&m);
return 1;
}
static void *w(void *arg) { (void)arg; withdraw(80); return NULL; }
int main(void) {
pthread_t a, b;
pthread_create(&a, NULL, bump, NULL); pthread_create(&b, NULL, bump, NULL);
pthread_join(a, NULL); pthread_join(b, NULL);
printf("hits = %d (expected 200000)\n", hits);
pthread_barrier_init(&both_checked, NULL, 2);
pthread_create(&a, NULL, w, NULL); pthread_create(&b, NULL, w, NULL);
pthread_join(a, NULL); pthread_join(b, NULL);
printf("balance = %d (should never be negative)\n", balance);
return 0;
}
Compiled and run with gcc:14 (GCC 14.4, aarch64 Linux container), five runs of gcc -O1 -pthread race.c -o r && ./r (each run prints both lines; the hits line is timing-dependent, so your five runs will differ):
hits = 100000 (expected 200000)
balance = -60 (should never be negative)
hits = 100000 (expected 200000)
balance = -60 (should never be negative)
hits = 100000 (expected 200000)
balance = -60 (should never be negative)
hits = 200000 (expected 200000)
balance = -60 (should never be negative)
hits = 100000 (expected 200000)
balance = -60 (should never be negative)
Note the fourth run: the plain int race printed the "right" answer once. That is the point of the next paragraph: the program is wrong on every run, and only the symptom varies.
Why 100000 in four of five runs at -O1? A register is a storage cell inside the CPU that is much faster than memory. The compiler is allowed to assume no data race, so it kept the counter in a register (it hoisted the load and store out of the loop, meaning it moved them before and after the loop instead of repeating them every iteration): the generated bump loads hits once, adds 100000, and stores once (I read the gcc -O1 -S output: one ldr, one str, a register loop between them). Walk through it with illustrative timing: thread A loads hits (0) into a register and adds 1 a hundred thousand times in the register, so the register holds 100000, then stores 100000 to memory; thread B did the same, starting from its own load of 0, and stores 100000 too. If the two threads overlap, both loaded 0, so whichever store lands last writes the same 100000 and one thread's whole contribution is overwritten. If one thread happens to finish completely before the other starts (thread start-up is slow compared with a 100000-iteration register loop, but it can happen, as in the fourth run), the second loads 100000 and stores 200000 and the symptom disappears for that run. So the result is 100000 or 200000 depending on timing, never a reliable total. In the ldr/str reading, ldr is the Arm instruction that loads from memory into a register and str stores a register back, so seeing only one of each around the loop is the evidence that the counter lived in the register. At -O0 the same program loses a variable amount: three runs printed 118833, 135721 and 125027. Both are "correct" outcomes of undefined behaviour, which is the practical meaning of UB: you cannot predict the symptom.
Under TSan (gcc -O1 -g -fsanitize=thread -pthread race.c -o rt && ./rt) the first part is reported as a data race at race.c:6 in bump (a read and a previous write by the two threads) and the count prints 200000, because instrumentation changes the code the compiler generates. A TSan data-race report names the kind of problem, then gives two blocks, one for the access that triggered it (read or write, its thread, its function and file:line) and one for the earlier conflicting access in the other thread, plus the location of the variable; two accesses to one address from two threads with no ordering between them is the whole diagnosis. The summary line is ThreadSanitizer: reported 1 warnings. Part 2 produced balance = -60 in that run too, and TSan said nothing about it: the accesses are all ordered by the mutex, so there is no data race to report. TSan's documentation describes the tool as one that "detects data races", so a clean TSan run says nothing about check-then-act bugs.
Why -60: both withdrawals checked 100 >= 80 before either subtracted, then 100 - 80 - 80 = -60. The fix is to make check and update one critical section (or a compare-and-swap loop on the balance):
lock; if (balance >= amt) balance -= amt, ok = 1; unlock
Why code can be free of data races and still be wrong
Synchronizing each variable protects the memory, not the rule that relates several operations. Typical shapes: check-then-act (above), read-modify-write split across two lock regions, "if absent then insert" on a locked map, two separately atomic variables that must change together, and iterating a collection whose size was read earlier.
The same race between a task and an interrupt service routine (ISR)
A counter updated by both a task and an ISR is the same defect. volatile stops the compiler from caching the variable, but cppreference notes that volatile access is suitable for communication with a signal handler, "but not with another thread of execution". count++ is still a load, an add and a store, and an ISR that fires between the load and the store loses an update; the fix is a short critical section (a stretch of code only one thread or interrupt handler may be inside at a time) with interrupts masked, or a hardware atomic read-modify-write where the core has one.
Trade-offs and pitfalls
- "Benign" data races do not exist in C/C++: even a racy flag can be hoisted out of a loop, as the register-resident counter above shows.
- Removing a data race with atomics does not fix a race condition; ask what invariant ties the operations together.
- Do not rely on a test passing: with a two-instruction window, a failure may need millions of iterations; use TSan for data races and invariant checks plus forced interleavings (as the barrier does) for logic races.
What is a counting semaphore? Describe wait and signal, how it differs from a binary semaphore, and a realistic use such as limiting concurrent access to a scarce resource. What goes wrong with fairness or misuse?
Sample Answer
Direct answer
A counting semaphore is a counter plus a wait queue, managed by two operations. Wait (also called P, down or acquire) blocks until the counter is above zero, then decrements it. Signal (V, up, release or post) increments the counter and wakes a waiter if there is one. The counter's initial value is the number of "permits" you have. A binary semaphore is the same thing limited to 0 or 1. Unlike a mutex, a semaphore has no owner: any thread may signal it. Typical use: limit concurrent access to a scarce resource, such as at most 3 simultaneous database connections.
How it behaves
With initial count 3:
| Step | Count | Effect |
|---|---|---|
| Thread 1 waits | 3 to 2 | proceeds |
| Thread 2 waits | 2 to 1 | proceeds |
| Thread 3 waits | 1 to 0 | proceeds |
| Thread 4 waits | 0 | blocks |
| Thread 1 signals | 0 to 1, then thread 4 takes it | thread 4 proceeds |
The C++ reference says exactly this about std::counting_semaphore: acquire decrements the counter or blocks until it can, release increments it and unblocks acquirers, and unlike std::mutex it is not tied to threads of execution, so acquiring and releasing can happen on different threads.
Counting vs binary
| Counting | Binary | |
|---|---|---|
| Range | 0 to N | 0 or 1 |
| Typical use | Pool of N identical resources; counting events so none is lost | One-shot signal between two threads; mutual exclusion in the simplest case |
| Signalling twice before anyone waits | Count becomes 2: both events remembered | The second signal is not remembered as a second event, so one event is remembered. What the API does with the extra signal depends on the platform: std::binary_semaphore makes a release beyond its maximum a precondition violation (undefined behaviour, so never rely on it), FreeRTOS's give call returns a failure code, and POSIX has no binary semaphore type, so sem_post would simply count up to 2 |
std::binary_semaphore is just std::counting_semaphore<1>.
A realistic use: limiting concurrent access
#include <atomic>
#include <chrono>
#include <cstdio>
#include <semaphore>
#include <thread>
#include <vector>
using namespace std::chrono_literals;
std::counting_semaphore<8> slots(3); // at most 3 threads may use the scarce resource
std::atomic<int> inside{0}, max_inside{0};
void use_resource(bool fail_early_bug) {
slots.acquire(); // wait (P): count 3 -> 2 -> 1 -> 0, then block
int now = ++inside;
int seen = max_inside.load();
while (now > seen && !max_inside.compare_exchange_weak(seen, now)) {}
std::this_thread::sleep_for(20ms);
--inside;
if (fail_early_bug) return; // BUG: returns without giving the permit back
slots.release(); // signal (V): count + 1, wakes one waiter
}
int main() {
std::vector<std::thread> ts;
for (int i = 0; i < 10; i++) ts.emplace_back(use_resource, false);
for (auto& t : ts) t.join();
std::printf("10 threads, 3 permits: max concurrent = %d\n", max_inside.load());
// Misuse: three callers hit an error path that skips release(). The pool is now empty.
std::vector<std::thread> bad;
for (int i = 0; i < 3; i++) bad.emplace_back(use_resource, true);
for (auto& t : bad) t.join();
bool got = slots.try_acquire_for(200ms);
std::printf("after 3 leaked permits, a new acquire succeeds = %s\n", got ? "yes" : "no (timed out)");
// Binary semaphore: a one-shot signal between threads, released by a different thread.
std::binary_semaphore ready(0);
std::thread producer([&] { std::this_thread::sleep_for(10ms); ready.release(); });
ready.acquire();
producer.join();
std::printf("binary semaphore signalled by another thread: ok\n");
}
Compiled with g++ -std=c++20 -O2 -Wall -Wextra -pthread sem.cpp (and again with -fsanitize=thread, same output, no reports) in a GCC 14 container:
10 threads, 3 permits: max concurrent = 3
after 3 leaked permits, a new acquire succeeds = no (timed out)
binary semaphore signalled by another thread: ok
Ten threads compete for three permits and never more than three are inside at once. The second line shows the classic misuse: three callers hit an early-return path that skips release, and the permits are gone for good, so every later caller waits until it times out.
ISR-to-task signalling vs resource-pool counting
An ISR (interrupt service routine: code the hardware runs when an interrupt fires) must never block, so it cannot take a lock. It can signal a semaphore, and a task blocked on that semaphore wakes to do the longer processing. The POSIX specification makes sem_post async-signal-safe, meaning it may be called from a signal handler (the user-space cousin of an interrupt handler), which is what makes signalling from such a context legitimate; on an RTOS (real-time operating system) use the ISR-specific give call the RTOS documents.
- Binary semaphore (initial 0): "an event happened". If two interrupts fire before the task runs, the second signal is not counted, so the task handles one event. That is fine when the task re-reads the device state anyway.
- Counting semaphore (initial 0): each interrupt adds one, so the task runs once per event and none is lost, provided the count cannot overflow its maximum.
- Resource pool (initial N): tasks wait to claim one of N buffers and signal to return it. Here the count means "free items".
Fairness and misuse
- Who wakes up. POSIX says
sem_post, under a real-time scheduling policy (the POSIX real-time scheduling policies SCHED_FIFO, where a thread runs until it blocks or yields, and SCHED_RR, which adds a fixed time slice among threads of equal priority; SCHED_SPORADIC, where supported, follows the SCHED_FIFO rule), unblocks the highest-priority waiter, and the one that has waited longest among equals; under other policies POSIX leaves the choice to the implementation. The C++ reference documents no wake-up order at all, so do not rely on first-come-first-served. A waiter can in principle be passed over repeatedly (starvation); if you need strict arrival order, queue tickets explicitly (each waiter takes a number and is served in number order). - Leaking a permit (shown above): release in a scope guard (a small object whose destructor gives the permit back on every exit path), not by hand on each path.
- Signalling without waiting inflates the count above the real number of resources, so more users get in than exist.
- A semaphore as a mutex. With no owner, the system does not know whom to boost to avoid priority inversion (a high-priority thread stuck behind a low-priority lock holder that a medium-priority thread keeps preempting), and any thread can release it by mistake.
- Waiting while holding another resource can deadlock: a thread holding permit A waits for permit B while another does the reverse.
Explain acquire and release semantics and how they differ from sequential consistency. Give an example where a weaker ordering permits a reordering that the stronger one prevents, and say what the performance trade-off is.
Sample Answer
Direct answer
Release/acquire is a pairwise guarantee: when thread B's acquire load reads the value written by thread A's release store of the same variable, everything A did before that store is visible to B after that load (the store synchronizes-with the load: this is the C++ name for exactly that release-reads-from-acquire pairing). The guarantee flows through that one variable: it relates this particular store-load pair, and it gives no ordering between a release store and a later acquire load of a different variable. Sequential consistency (seq_cst) adds a single total order over all seq_cst operations that every thread agrees on, which is what makes "my write is visible before my next read" hold across different variables. The weaker order permits a reordering the stronger prevents: a release store followed by an acquire load of a different variable may be reordered, so in the store buffering pattern both threads can read the old value of the other's variable; with seq_cst that outcome is impossible. The trade-off is cost: seq_cst may need a full barrier on a store, release/acquire often does not.
The orders in common use
C++ defines six orders. The sixth, consume, is in practice treated as acquire by compilers and is left out of the table. The orders interviewers ask about most are relaxed (no ordering), acquire/release (the pairwise handoff) and seq_cst (the default); acq_rel is the two-in-one for read-modify-write operations.
| Order | Applies to | What it guarantees | Typical use |
|---|---|---|---|
relaxed | load, store, read-modify-write (RMW) | Atomicity only; no ordering with other accesses. | Counters, statistics. |
acquire | load (and RMW) | No later read or write in this thread moves before it; pairs with a release. | Taking a lock, consuming a published value. |
release | store (and RMW) | No earlier read or write in this thread moves after it. | Releasing a lock, publishing data. |
acq_rel | RMW | Both, in one operation. | fetch_sub that drops a reference count (the thread that takes it to zero must see every other thread's writes to the object before freeing it; the increment can be relaxed), exchange on a lock word. |
seq_cst | everything | The above, plus one global total order of all seq_cst operations. | Default; Dekker-style flags; anything involving several variables. |
The C++ reference states the last one precisely: "There is a single total order S on all memory_order_seq_cst operations, including fences" (S is one imaginary list of all seq_cst operations that every thread agrees on), and S is consistent with the modification order of every atomic object and with strongly happens-before (the C++20 refinement of happens-before).
Example where weaker permits what stronger prevents (store buffering)
Two threads: T0 does x = 1; r0 = y; and T1 does y = 1; r1 = x;, all variables starting at 0. With seq_cst, r0 == 0 && r1 == 0 is impossible: in the total order one of the stores comes first, and the other thread's later load must see it. With release stores and acquire loads it is allowed: each thread's store can still be sitting in its store buffer when its own later load runs, because release does not order an earlier store against a later load of a different variable. A store buffer is a small queue inside each core where its recent writes wait before they become visible to other cores; the core's own later reads can proceed without waiting for that queue to drain. A hand trace with both variables starting at 0:
- T0 executes
x = 1: the write enters T0's store buffer. Other cores still seex == 0. - T1 executes
y = 1: the write enters T1's store buffer. Other cores still seey == 0. - T0 executes
r0 = y: it readsyfrom memory, which still holds 0, sor0 = 0. - T1 executes
r1 = x: it readsxfrom memory, which still holds 0, sor1 = 0. - Both buffers drain and the stores become visible, too late for either read.
The outcome r0 == 0 && r1 == 0 therefore has a real execution behind it. A seq_cst store (on x86-64, the xchg instruction described below) makes the core wait for its buffer to drain before the next read, which closes this gap. The program counts how often the "impossible" outcome happens (reading guide: Slot holds one x/y pair per round, padded with alignas so rounds do not share a cache line; the start counter makes both threads begin together; run<STORE, LOAD> is the same test parameterized by the memory order; bad counts rounds where both reads saw 0):
// Store buffering. T0: x = 1; r0 = y. T1: y = 1; r1 = x. Bad outcome: r0 == 0 && r1 == 0
#include <atomic>
#include <cstdio>
#include <thread>
using std::memory_order_acquire; using std::memory_order_release; using std::memory_order_seq_cst;
using std::memory_order;
constexpr int ROUNDS = 1 << 20, REPEATS = 8;
struct alignas(256) Slot { std::atomic<int> x{0}; alignas(128) std::atomic<int> y{0}; };
static Slot slots[ROUNDS];
static int r0[ROUNDS], r1[ROUNDS];
template <memory_order STORE, memory_order LOAD>
long run() {
long bad = 0;
for (int rep = 0; rep < REPEATS; ++rep) {
for (auto& s : slots) { s.x.store(0, std::memory_order_relaxed); s.y.store(0, std::memory_order_relaxed); }
std::atomic<int> start{0};
std::thread t0([&] {
start.fetch_add(1); while (start.load() < 2) {}
for (int i = 0; i < ROUNDS; ++i) { slots[i].x.store(1, STORE); r0[i] = slots[i].y.load(LOAD); }
});
std::thread t1([&] {
start.fetch_add(1); while (start.load() < 2) {}
for (int i = 0; i < ROUNDS; ++i) { slots[i].y.store(1, STORE); r1[i] = slots[i].x.load(LOAD); }
});
t0.join(); t1.join();
for (int i = 0; i < ROUNDS; ++i) bad += (r0[i] == 0 && r1[i] == 0);
}
return bad;
}
int main() {
long n = (long)ROUNDS * REPEATS;
printf("release store, acquire load bad=%ld of %ld\n", run<memory_order_release, memory_order_acquire>(), n);
printf("seq_cst store, seq_cst load bad=%ld of %ld\n", run<memory_order_seq_cst, memory_order_seq_cst>(), n);
}
In a 64-bit x86-64 Linux container (emulated on an Apple-silicon host; g++ -std=c++20 -O2 litmus_sb.cpp -o ls && ./ls) one run printed (the nonzero count varies each run; the zero is guaranteed):
release store, acquire load bad=819003 of 8388608
seq_cst store, seq_cst load bad=0 of 8388608
On the 64-bit Arm container the release/acquire line printed bad=0 in the same test. That does not make it safe: the C++ rules still allow the outcome, and the compiler maps both orders to the same instructions here (see the table below), so no observation there proves anything.
What the orders cost
g++ 14.4.0 -O2 -c on the functions in this file, disassembled with objdump -d --no-show-raw-insn:
#include <atomic>
std::atomic<int> v;
void store_relaxed(int x) { v.store(x, std::memory_order_relaxed); }
void store_release(int x) { v.store(x, std::memory_order_release); }
void store_seq_cst(int x) { v.store(x, std::memory_order_seq_cst); }
int load_relaxed() { return v.load(std::memory_order_relaxed); }
int load_acquire() { return v.load(std::memory_order_acquire); }
int load_seq_cst() { return v.load(std::memory_order_seq_cst); }
| Operation | x86-64 | 64-bit Arm (AArch64) |
|---|---|---|
| store relaxed | mov | str |
| store release | mov | stlr |
| store seq_cst | xchg | stlr |
| load relaxed | mov | ldr |
| load acquire | mov | ldar |
| load seq_cst | mov | ldar |
(stlr and ldar are Arm's store-release and load-acquire instructions.) On x86-64, release and acquire cost nothing beyond a plain move, but a seq_cst store is an xchg, which implies a full memory barrier (an instruction that stops the core from letting later memory operations overtake earlier ones) and waits for the store buffer to drain; this is the price of making the store buffering outcome impossible. On AArch64 with this compiler, seq_cst and release/acquire compile to the same instructions, so there is no instruction-level difference; the compiler may still move less code around a seq_cst operation. These are instruction counts, not timings: measure your own workload before choosing.
Choosing
My default is seq_cst: it is the only order whose behaviour you can reason about without a model. Move to release/acquire when the algorithm is a clear one-variable handoff (lock release/acquire, publish-then-flag, the SPSC ring), and to relaxed for counters nothing else depends on. What flips the choice: a profile showing the seq_cst store on a hot path on x86-64, or an algorithm needing several variables to be seen in one global order (flags in Dekker or Peterson style locks, the classic two-thread algorithms in which each thread raises its own flag and then checks the other's before entering; they rely on exactly the store-then-load ordering that store buffering breaks), where release/acquire is wrong and seq_cst (or explicit fences, which are standalone ordering instructions such as std::atomic_thread_fence) is required.
Pitfalls
Reasoning "it worked on x86-64" for release/acquire code that only needs weaker hardware ordering; pairing a release with a relaxed load (no synchronizes-with edge); and relaxing the order of a pattern that involves two variables.
What is an atomic operation? Name the primitives you would expect a platform to offer, and describe one case where an atomic beats a mutex and one where it does not.
Sample Answer
Direct answer
An atomic operation is one that other threads can only observe as either not started or fully finished, never half done. A read-modify-write such as counter++ is normally three steps (load, add, store), so two threads can both load the same old value and one update is lost; an atomic increment does all three as one indivisible step. Atomics beat a mutex for a single independent variable (a statistics counter, a flag). They do not help when an invariant spans several variables or a check and an action must be made together.
Primitives a platform typically offers
Compare-and-swap and fetch-and-modify do most of the practical work; the other four are the simplest cases of them or the hardware pieces they are built from.
| Primitive | Meaning | Example names |
|---|---|---|
| Atomic load / store | Read or write a value so it is never torn (observed with some bytes from an old write and some from a new one) | std::atomic<T>::load/store, C11 atomic_load |
| Exchange | Store a new value and return the old one, atomically | exchange |
| Compare-and-swap (CAS) | Store a new value only if the current value equals an expected one; report whether it did | compare_exchange_weak/strong, GCC __atomic_compare_exchange_n |
| Fetch-and-modify | Atomically add, subtract, AND, OR or XOR, returning the old value | fetch_add, fetch_sub, fetch_or, GCC __atomic_fetch_add |
| Test-and-set | Atomically set a flag and return whether it was already set; the building block of a spinlock (a lock whose waiters loop re-checking the flag instead of sleeping) | std::atomic_flag::test_and_set |
| Load-linked / store-conditional | A hardware pair used on ARM, RISC-V and Power CPUs to build the others. Load-linked reads the value and marks the address; store-conditional writes only if nothing wrote that location since, and otherwise fails so the code retries. A fetch-add becomes: load-linked, add, store-conditional, retry on failure | ldxr/stxr (ARMv8.0-A), lr/sc (RISC-V), lwarx/stwcx. (Power): how CAS and fetch-add are built on those CPUs. ARMv8.1-A adds single-instruction atomics (ldadd, cas), and GCC's default outline-atomics helpers on AArch64 (the -O2 build of this program calls __aarch64_ldadd8_relax) pick the load/store-exclusive or the single-instruction form at run time |
Compiler built-ins matter on embedded toolchains: GCC documents the __atomic built-ins as approximately matching the requirements of the C++11 memory model and says new code should use them rather than the older __sync built-ins (a family that predates the C++11 memory model). If the hardware has no lock-free instruction for an operation (a single hardware instruction that does the whole operation, with no lock taken behind the scenes), GCC emits a call to an external routine (its libatomic support library) instead, which may be implemented with a lock, so check lock-freedom with std::atomic<T>::is_always_lock_free for your target type.
Where an atomic beats a mutex
A statistics counter incremented by four threads. A mutex works but makes contending threads queue, and a waiting thread may be put to sleep (a context switch: the operating system's scheduler swaps another thread onto the CPU), which is slow if the lock is held only for one addition. An atomic fetch_add never blocks and cannot deadlock.
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <string>
#include <thread>
#include <vector>
constexpr int THREADS = 4, PER_THREAD = 100000;
// (1) A plain counter: the read-modify-write is three steps (load, add, store).
// Run "./atomics plain" for the racy version, "./atomics" for the atomic one.
long plain_counter = 0;
std::atomic<long> atomic_counter{0};
int main(int argc, char** argv) {
bool use_plain = argc > 1 && std::string(argv[1]) == "plain";
std::vector<std::thread> ts;
for (int t = 0; t < THREADS; t++)
ts.emplace_back([&] {
for (int i = 0; i < PER_THREAD; i++) {
if (use_plain) ++plain_counter; // data race
else atomic_counter.fetch_add(1, std::memory_order_relaxed); // atomic RMW
}
});
for (auto& t : ts) t.join();
long got = use_plain ? plain_counter : atomic_counter.load();
std::printf("%s: expected %d, got %s%ld\n", use_plain ? "plain" : "atomic",
THREADS * PER_THREAD, got == THREADS * PER_THREAD ? "" : "(lost updates) ", got);
std::printf("atomic<long> always lock-free: %d\n", (int)std::atomic<long>::is_always_lock_free);
// Compiler built-in form of the same operation, as used from C or embedded toolchains.
long builtin = 0;
__atomic_fetch_add(&builtin, 5, __ATOMIC_RELAXED);
std::printf("builtin result: %ld\n", builtin);
}
Built with g++ -std=c++20 -O2 -pthread in a GCC 14 container on arm64:
$ ./at plain
plain: expected 400000, got (lost updates) 134335
atomic<long> always lock-free: 1
builtin result: 5
$ ./at
atomic: expected 400000, got 400000
atomic<long> always lock-free: 1
builtin result: 5
The plain count lands far below 400,000 (typically somewhere around 100,000 to 200,000 here) and changes from run to run; the atomic version is exact. Compiling the same file with -fsanitize=thread makes ThreadSanitizer print WARNING: ThreadSanitizer: data race for the plain counter line and nothing for the atomic version. The counter is relaxed (memory_order_relaxed) because it only needs to be counted correctly, with no ordering against other data: the C++ reference describes relaxed operations as guaranteeing atomicity and modification order only.
Where an atomic does not beat a mutex
- A rule that spans two variables. A transfer that moves 50 from
checkingtosavingswhile keeping their total fixed needs both changes to be visible together. Making each variable atomic still lets another thread see the money gone from one account and not yet in the other, or approve two transfers against the same balance (a check-then-act race). One mutex around both updates, or packing both values into a single atomic word, fixes it. - A long or blocking critical section. Atomics cannot make a thread wait politely. Spinning on an atomic burns CPU, where a mutex lets the thread sleep.
- Complex structures. Lock-free linked structures bring the ABA problem (a value changes A to B and back to A, so a CAS wrongly succeeds) and memory-reclamation problems. A mutex is far easier to get right.
Cost of choosing atomics in a hot path
Each atomic needs a justified memory order, which says how much ordering it imposes on the other reads and writes around it: relaxed guarantees only that this one operation is atomic; acquire/release is a pair, where a release store publishes everything the thread wrote before it and an acquire load that sees that store also sees those writes; sequentially consistent (seq_cst) adds a single order of all such operations that every thread agrees on. A reviewer must reason about every one of these choices, whereas a mutex gives one simple rule. Recommendation: start with a mutex; use atomics for independent counters and flags, defaulting to the strongest order (seq_cst) unless profiling shows it matters and you can explain why a weaker one is correct. What would flip it: a measured contention problem on a single variable with no invariant tying it to other data.
Unlock Full Question Bank
Get access to all 22 Concurrency, Synchronization & Deadlock interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.