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.
Explain the ABA problem using a pop from a lock-free stack. Why can a compare-and-swap succeed and still corrupt the structure, and how can it be prevented?
Sample Answer
Direct answer
The ABA problem is a compare-and-swap (CAS) succeeding because a location holds the same value as before, although the structure around it changed in between. Thread 1 reads the top of a lock-free stack as A, is preempted (the scheduler pauses it mid-operation); other threads pop A, pop B, free B and push A back; thread 1's CAS (head == A?) succeeds and installs the stale next pointer (B), which now points at freed memory. Prevent it either by making the value carry history (a version tag packed with the pointer or index, so A-with-tag-3 is not A-with-tag-6) or by never freeing or reusing a node while another thread might still hold a pointer to it; a tag alone leaves the read of a freed node unsafe, so tagged designs over heap nodes also need a fixed pool or a reclamation scheme. The version tag is the core fix for the CAS itself; the table below lists the ways to make freeing safe (hazard pointers, epoch-based reclamation, RCU, a fixed node pool), each explained there.
The pop that breaks
A lock-free stack (a Treiber stack, the standard lock-free stack design) is a singly linked list whose head pointer is updated by CAS. The textbook pop:
old = head
do { if (old == NULL) return NULL; next = old->next; } // step 1: read next
while (!CAS(&head, &old, next)); // step 2: swing head from old to next
It is correct only if "head still equals old" implies "old->next is still next". That is false when old can leave the stack and come back.
Starting from a stack a -> b -> c:
| Step | Thread T1 | Thread T2 | State |
|---|---|---|---|
| 1 | reads old = a, next = b (not yet CAS) | a -> b -> c | |
| 2 | (preempted) | pop a, pop b, free(b) | c |
| 3 | push a back | a -> c | |
| 4 | CAS(head, a, b) succeeds: head == a | head = b (already freed) |
The CAS only compared head with a, and a really is at the head again. Everything T1 knew about what follows a is stale. Two failures follow: the stack's head now points at a node that is no longer in the stack, and the next operation reads b->next from freed memory (a use-after-free: reading or writing memory after it was given back to the allocator, where its contents may be anything).
Reproduced deterministically, and the fix, in a Linux container
A real race needs lucky timing, so this program plays the two threads' steps in a fixed order on one thread, using the real atomic operations. Part 2 is the fix (an index plus a tag packed into one 64-bit atomic over a small node array), run through the same interleaving. In part 2 the 64-bit word is the tag in its high 32 bits and the node index in its low 32 bits: pack(tag, idx) shifts the tag left by 32 and ORs in the index, idx_of keeps the low half and tag_of shifts the high half down. For example pack(3, 0) is 3 x 2^32 + 0 = 12,884,901,888, the word T1 reads: tag 3, index 0. T2's two pops and one push each add 1 to the tag (3, then 4, 5, 6) while the index goes 0, then 1, then 2, then 0 again, so the head word becomes pack(6, 0): the same index as before but a different word, and T1's compare with pack(3, 0) fails. Part 1 is the pointer version.
#include <stdatomic.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/* ---------- Part 1: pointer-based Treiber stack, scripted ABA interleaving ---------- */
typedef struct Node { int val; struct Node *next; } Node;
static _Atomic(Node *) head;
static void push(Node *n) {
Node *old = atomic_load(&head);
do { n->next = old; } while (!atomic_compare_exchange_weak(&head, &old, n));
}
static Node *pop(void) { /* the textbook pop */
Node *old = atomic_load(&head), *next;
do {
if (!old) return NULL;
next = old->next; /* (1) read next */
} while (!atomic_compare_exchange_weak(&head, &old, next)); /* (2) CAS */
return old;
}
static void part1(void) {
Node *a = malloc(sizeof *a), *b = malloc(sizeof *b), *c = malloc(sizeof *c);
a->val = 1; b->val = 2; c->val = 3;
push(c); push(b); push(a); /* stack: a -> b -> c */
/* T1 starts pop: reads old = a, next = b ... then is descheduled before its CAS. */
Node *t1_old = atomic_load(&head), *t1_next = t1_old->next;
/* T2 runs to completion: pop a, pop b (and free it), push a back. Stack is now a -> c. */
Node *x = pop(); Node *y = pop(); free(y); push(x);
printf("part1: T2 done; head is again a (same address): %s; real stack is a -> c\n", atomic_load(&head) == a ? "yes" : "no");
/* T1 resumes: head == a, so its CAS succeeds, installing the stale next = b (freed). */
Node *expected = t1_old;
int ok = atomic_compare_exchange_strong(&head, &expected, t1_next);
printf("part1: T1's CAS succeeded: %s; head now points at the freed node b\n", ok ? "yes" : "no");
Node *p = pop(); /* next operation reads head->next through the freed node */
printf("part1: next pop returned %p\n", (void *)p);
}
/* ---------- Part 2: index + tag packed into one 64-bit atomic ---------- */
#define NIL 0xFFFFFFFFu
typedef struct { int val; uint32_t next; } Slot;
static Slot slots[3];
static _Atomic uint64_t top2; /* high 32 bits: tag, low 32 bits: index */
static uint64_t pack(uint32_t tag, uint32_t idx) { return ((uint64_t)tag << 32) | idx; }
static uint32_t idx_of(uint64_t v) { return (uint32_t)v; }
static uint32_t tag_of(uint64_t v) { return (uint32_t)(v >> 32); }
static void push2(uint32_t i) {
uint64_t old = atomic_load(&top2);
do { slots[i].next = idx_of(old); } while (!atomic_compare_exchange_weak(&top2, &old, pack(tag_of(old) + 1, i)));
}
static int pop2(uint32_t *out) {
uint64_t old = atomic_load(&top2);
do {
if (idx_of(old) == NIL) return 0;
uint32_t nxt = slots[idx_of(old)].next;
if (atomic_compare_exchange_weak(&top2, &old, pack(tag_of(old) + 1, nxt))) { *out = idx_of(old); return 1; }
} while (1);
}
static void part2(void) {
atomic_store(&top2, pack(0, NIL));
push2(2); push2(1); push2(0); /* stack: 0 -> 1 -> 2 */
uint64_t t1_old = atomic_load(&top2); /* T1 reads top = (tag 3, idx 0) and next = 1, then stalls */
uint32_t t1_next = slots[idx_of(t1_old)].next;
uint32_t x, y; pop2(&x); pop2(&y); push2(x); /* T2: pop 0, pop 1, push 0 back */
printf("part2: top index is again %u, but tag went %u -> %u\n", idx_of(atomic_load(&top2)), tag_of(t1_old), tag_of(atomic_load(&top2)));
uint64_t expected = t1_old;
int ok = atomic_compare_exchange_strong(&top2, &expected, pack(tag_of(t1_old) + 1, t1_next));
printf("part2: T1's CAS succeeded: %s\n", ok ? "yes" : "no (stale tag, so T1 must re-read)");
printf("part2: lock-free? %s\n", atomic_is_lock_free(&top2) ? "yes" : "no");
}
int main(void) { setvbuf(stdout, NULL, _IONBF, 0); part2(); part1(); return 0; }
gcc -O1 -g -Wall -Wextra -fsanitize=address,undefined aba.c -o aba && ./aba in a gcc:14 container (aarch64); the program turns off stdout buffering because AddressSanitizer aborts the process. The part lines and the AddressSanitizer summary:
part2: top index is again 0, but tag went 3 -> 6
part2: T1's CAS succeeded: no (stale tag, so T1 must re-read)
part2: lock-free? yes
part1: T2 done; head is again a (same address): yes; real stack is a -> c
part1: T1's CAS succeeded: yes; head now points at the freed node b
==12==ERROR: AddressSanitizer: heap-use-after-free on address 0x502000000038 ...
SUMMARY: AddressSanitizer: heap-use-after-free /w/aba.c:18 in pop
(The tag went from 3 to 6 because each of the three T2 operations, two pops and a push, adds 1.) With the pointer version the CAS succeeds and the next pop reads old->next from the freed node at line 18. AddressSanitizer is a compiler-inserted memory checker; "heap-use-after-free" is its name for exactly that, an access to heap memory (from malloc) after free. With the tagged version the same interleaving makes T1's CAS fail, and T1 would re-read the head and retry correctly.
In production code the "A comes back" step usually happens without the code doing it deliberately: free(a) then a later malloc returns the same address for a new node, so a new node looks like the old one to a pointer comparison.
Ways to prevent it
| Technique | How it prevents the failure | Cost / caveat |
|---|---|---|
| Version tag (counter) packed with pointer or index | A and A-again differ in the tag | Needs a double-width CAS (one atomic compare-and-swap over two machine words, such as a 16-byte pointer plus tag) for full pointers, or an index into a pool as above; the tag wraps (32 bits after 2^32 operations, in practice vanishingly rare but nonzero) |
| Node pool, never freed during the structure's life | A reused node is still a valid node | Memory is held; tag still needed for ABA (the value problem), the pool only fixes the use-after-free |
| Hazard pointers | A thread publishes the pointer it is about to dereference; a node is freed only when no hazard pointer names it | Extra bookkeeping per access, retire lists |
| Epoch-based reclamation / RCU (read-copy-update, the same idea used in the Linux kernel: readers run without locks and an old node is freed only after a grace period in which every reader has finished) | Nodes are freed only after every thread has passed a point at which it cannot still hold an old reference | A stalled thread delays reclamation |
| Use a lock | No ABA window | Not lock-free |
A tag stops the corrupting CAS; it does not by itself make freeing a node safe, because T1 may still dereference old->next of a node T2 just freed (reading old->next at step 1 is itself a hazard when nodes are freed). That second problem is safe memory reclamation (deciding when freeing a node can no longer hurt a thread still reading it). The two fixes overlap rather than always stack: a tag-based design needs a never-freed pool or a reclamation scheme to make the old->next read safe, while hazard pointers or epoch-based reclamation used alone also remove the ABA window, because a node that another thread may still reference is never freed and so its address cannot come back as a "new" node. Real implementations therefore choose tag plus index pool, or reclamation without a tag, not necessarily both.
Pitfalls
- Assuming load-linked/store-conditional (LL/SC, the CPU pair used on Arm and POWER instead of CAS: the store succeeds only if nothing wrote the location since the load) is always a way out. It detects any intervening write, so the stack's ABA does not arise on that primitive, but real hardware can fail the store for other reasons, and C++ and Rust code only see the CAS abstraction, so the portable answer is still the tag plus safe reclamation.
- Believing a successful CAS means "nothing changed". It means "the value I compared is the same".
- Tagging with a counter and also reusing freed memory immediately, which fixes the CAS but keeps the use-after-free.
- Skipping a
atomic_is_lock_freecheck on the packed type: a 16-byte (pointer + tag) CAS may not be lock-free on every platform; the index-plus-tag layout above fits in 64 bits (it printedlock-free? yeshere). - Testing with real threads only: a deterministic replay as above is the reliable way to prove a fix handles the interleaving.
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).
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.
Design a work-stealing scheduler for parallel tasks, like a fork-join pool. What does each worker's deque look like, which end does the owner use and which end do thieves use, how is a steal made safe without a global lock, and what keeps contention low?
Sample Answer
What a work-stealing scheduler is. A fork-join pool (Java's ForkJoinPool is the familiar one) runs many small tasks on a fixed set of worker threads. Instead of one shared queue that every worker fights over, each worker owns its own double-ended queue (a "deque", pronounced "deck"). A worker takes work from its own deque and only goes to other workers' deques when its own is empty. That is "stealing". Most of the time a worker touches only its own deque, so there is almost nothing to contend on.
1. What each worker's deque looks like. A circular array of task slots plus two integer indices: bottom (where the owner pushes and pops) and top (where thieves take from). The deque holds the tasks at indices top up to bottom - 1, stored at index mod capacity. top only ever grows (it is a 64-bit long, so wrap-around is not a practical concern), which matters later for the ABA problem (a value that changes A to B and back to A, fooling a compare-and-swap). bottom does not only grow: the owner's pop moves it back down by one each time it takes an item, and only the owner ever writes it.
2. Which end is used by whom.
- The owner pushes new tasks at the bottom and pops from the bottom. That is last-in-first-out (LIFO), like a stack. When a task forks children and then joins them, the owner immediately runs the most recently forked child, which is the one whose data is still in its CPU cache, and the recursion stays depth-first, so the deque stays small.
- Thieves take from the top, the opposite end. That is first-in-first-out for them, and the task at the top is the oldest one, which in divide-and-conquer code is the biggest remaining chunk (the root of the largest unexplored subtree). One steal therefore hands the thief a lot of work, so steals are rare. Using opposite ends also means owner and thief almost never want the same slot.
- The ForkJoinPool documentation confirms the default "locally stack-based" order for a worker's own tasks, and offers an
asyncModeflag for local first-in-first-out order for event-style tasks that are never joined.
3. How a steal is made safe without a global lock. The only slot owner and thief can fight over is the very last item. The rules:
- Only the owner writes
bottom; only the owner writes slots. Thieves never writebottomand never write slots. topis advanced by compare-and-swap (CAS: "settopto t+1 only if it still equals t, atomically"). A thief readstop, readsbottom, reads the slot attop, then CASestopfrom t to t+1. If the CAS fails, another thief (or the owner) took that task first, so this thief gives up (returns ABORT) and tries elsewhere. Becausetopnever goes backwards, a stale slot value can never be mistaken for a fresh one, so ABA does not arise ontop: a thief that readtop= 3 can only succeed with a CAS from 3 to 4 whiletopis still 3, and since the index only grows, 3 can never come back after it has been passed.- The owner's
pushwrites the slot first, then publishes it by storingbottom + 1with release semantics (release: everything written before this store is visible to a thread that reads the new value with acquire or stronger). The code below usesseq_cstfor this store, which is stronger than release and includes it, so its comment "release: publishes the slot write" names the property this store is relied on for. A thief that sees the newbottomis therefore guaranteed to see the task in the slot. - The owner's
popis the delicate one. It first storesbottom - 1(claiming the item), and only then readstop. Both sides do "write my index, then read the other side's index", which is the classic pattern that needs sequentially consistent ordering (seq_cst: all threads agree on one global order of these operations). With anything weaker, each side could read the other's old index, as if the other had not yet written. A hand trace with illustrative numbers: the deque holds two tasks,top= 3 andbottom= 5 (slots 3 and 4). Thief A steals slot 3 (topbecomes 4). Thief B readstop= 4 and a stalebottom= 5, so it plans to take slot 4. The owner meanwhile storesbottom= 4 and reads a staletop= 3; since 3 < 4 it concludes there are two or more items and takes slot 4 with no CAS. Both take slot 4. Under seq_cst this cannot happen: B's read ofbottombefore the owner's store, and the owner's read oftopbefore A's CAS, cannot both hold in one global order, so either B seesbottom= 4 and finds the deque empty, or the owner seestop= 4 and falls into the last-item CAS path. And for the last item itself: withtop= 3 andbottom= 4, the owner and a thief both try to movetopfrom 3 to 4 by CAS; only one CAS can succeed, so only one takes the task. If after the claimtopis still belowbottom, there are at least two items and the owner takes the slot with no CAS at all. If exactly one item remains (top == bottom), the owner must win a CAS ontopagainst any thief; the loser comes away empty-handed. Iftop > bottom, the deque was already empty.
This design is known as the Chase-Lev deque, after its authors. Here is a fixed-capacity version (no growth), compiled and run with GCC 14.4.0 in a Linux container. The ring size is a power of two, so & (CAP - 1) is the modulo. The code uses seq_cst on the index operations rather than separate fences, because ThreadSanitizer (TSan, the compiler's data-race detector) does not model standalone fences. That is simpler and slightly slower than the hand-tuned acquire/release plus fence version published for this algorithm, which is a different, more delicate design and is not reproduced here.
// Fixed-capacity Chase-Lev work-stealing deque (no resizing), seq_cst on the index operations.
#include <atomic>
#include <thread>
#include <vector>
#include <cstdio>
#include <cstdlib>
constexpr long CAP = 1 << 12; // power of two; owner must never hold more than CAP items
constexpr int EMPTY = -1, ABORT = -2;
struct Deque {
std::atomic<long> top{0}, bottom{0}; // thieves advance top; only the owner writes bottom
std::atomic<int> slot[CAP];
bool push(int x) { // owner only
long b = bottom.load(std::memory_order_relaxed), t = top.load(std::memory_order_acquire);
if (b - t >= CAP) return false; // full: a real pool would grow or run the task inline
slot[b & (CAP - 1)].store(x, std::memory_order_relaxed);
bottom.store(b + 1, std::memory_order_seq_cst); // release: publishes the slot write
return true;
}
int pop() { // owner only, LIFO end
long b = bottom.load(std::memory_order_relaxed) - 1;
bottom.store(b, std::memory_order_seq_cst); // announce the claim BEFORE reading top
long t = top.load(std::memory_order_seq_cst);
if (t > b) { bottom.store(b + 1, std::memory_order_relaxed); return EMPTY; }
int x = slot[b & (CAP - 1)].load(std::memory_order_relaxed);
if (t == b) { // last item: race the thieves for it
#ifndef BROKEN
if (!top.compare_exchange_strong(t, t + 1, std::memory_order_seq_cst)) x = EMPTY;
#endif
bottom.store(b + 1, std::memory_order_relaxed);
}
return x;
}
int steal() { // any thread, FIFO end
long t = top.load(std::memory_order_seq_cst);
long b = bottom.load(std::memory_order_seq_cst);
if (t >= b) return EMPTY;
int x = slot[t & (CAP - 1)].load(std::memory_order_relaxed);
if (!top.compare_exchange_strong(t, t + 1, std::memory_order_seq_cst)) return ABORT;
return x;
}
};
int main() {
const int N = 200000, THIEVES = 3;
static Deque d;
static std::atomic<int> seen[N];
std::atomic<bool> done{false};
auto take = [&](int x) { if (x >= 0) seen[x].fetch_add(1, std::memory_order_relaxed); };
std::vector<std::thread> th;
for (int i = 0; i < THIEVES; i++) th.emplace_back([&] {
while (!done.load(std::memory_order_acquire)) take(d.steal());
});
int next = 0;
while (next < N) { // owner: push a burst, pop part of it, repeat
for (int k = 0; k < 7 && next < N; k++) if (d.push(next)) next++;
for (int k = 0; k < 4; k++) take(d.pop());
}
for (int x; (x = d.pop()) != EMPTY;) take(x);
while (true) { int x = d.steal(); if (x == EMPTY) break; take(x); }
done.store(true, std::memory_order_release);
for (auto& t : th) t.join();
long missing = 0, dup = 0;
for (int i = 0; i < N; i++) { int c = seen[i].load(); if (c == 0) missing++; else if (c > 1) dup++; }
std::printf("tasks=%d missing=%ld duplicated=%ld\n", N, missing, dup);
return (missing || dup) ? 1 : 0;
}
What was run and what it showed.
g++ -std=c++17 -O1 -g -Wall -Wextra -fsanitize=thread deque.cpp -o t, then./tfive times: every run printedtasks=200000 missing=0 duplicated=0and TSan reported no data race (3 thieves plus the owner, 200,000 task ids, each counted in a per-id array).g++ -std=c++17 -O2 -Wall -Wextra deque.cpp -o o, three runs: same line,missing=0 duplicated=0.- To prove the harness can fail, the same program was compiled with
-DBROKEN(which removes the last-item CAS frompop). Over repeated runs of both the-O2build and the TSan-O1build the duplicate count was in the thousands and varied widely from run to run, and it was never 0. The exact count is timing-dependent and is not the point; the point is that it was never 0. So the CAS on the last item is the load-bearing line, and the test catches its absence. - Caveat: this ran natively in an aarch64 Linux container (a weakly ordered CPU, which is a good place to find ordering bugs). Passing tests is evidence, not a proof; a production deque would also get model checking or a long stress run on x86-64 as well.
4. What keeps contention low.
- Owner operations (
push, andpopwhen two or more items remain) never need a compare-and-swap and never wait for another thread, but they are not free: both readtop, the line thieves write, and the seq_cst store tobottomthatpopdepends on compiles with GCC 14-O2on x86-64 to anxchginstruction (an implicitly locked read-modify-write, regenerated withg++ -O2 -S), while on AArch64 it is a plain release-store instruction. Production deques avoid that cost with the weaker acquire/release-plus-fence formulation, which the code shown here does not use. - Thieves are the exception. They only touch another worker's
topandbottom, and only when they are idle, so busy workers are not slowed. - Steal from the oldest end: big chunks, so few steals per unit of work.
- Choose victims (the workers being stolen from) randomly (or try a few random victims, then back off and park the thread, meaning put it to sleep until woken): this spreads thieves across deques instead of all hammering worker 0.
- Keep
topandbottomon separate cache lines (pad to 64 bytes on typical x86-64 and arm64 parts; check your target). Otherwise the owner's writes tobottomand thieves' CASes ontopbounce one line between cores (false sharing). The fixed-capacity code above declares the two indices side by side and does not add this padding. - A failed CAS returns ABORT instead of spinning. The thief just moves to another victim.
- A thief that finds every deque empty should not spin forever: after some failed rounds it parks (sleeps on a condition variable or a futex, the Linux kernel primitive that lets a thread sleep on an address until another thread wakes it) and a push wakes it. Waking is the one place a lock or a kernel call re-enters, and it is off the hot path.
5. What this sketch leaves out, and how a production deque handles it.
- Growth: when
bottom - topreaches capacity, a production deque allocates a bigger array, copies the live range, and publishes the new array pointer. Old arrays cannot be freed while a thief might still be reading them, so they are retired and freed later (safe memory reclamation: for example epochs, where an array is freed only after every thread has moved past the moment it was retired, or hazard pointers, where a thread announces the address it is reading and the freer skips announced addresses), or the pool simply runs the task inline when the deque is full. - Task type: slots here are
intids so the slot reads are atomic and TSan-clean. A real pool stores task pointers instd::atomic<Task*>slots for the same reason. A thief reads a slot before its CAS succeeds, so the slot read must be an atomic read, and a result that loses the CAS is discarded. - Joins: a worker that waits for a child it forked should keep executing other tasks (its own deque first, then steals) instead of blocking, otherwise a small pool can starve itself.
- Fairness and idle handling, plus exceptions inside tasks, are policy layers on top of the deque.
How to say it in an interview. One sentence per decision: per-worker deque so there is no global lock; owner LIFO for cache locality and small depth; thieves FIFO for big chunks and rare steals; only the last element is contended and it is settled by one CAS on top; and the pop-claims-then-reads-top step needs seq_cst. Then offer the failure you tested: remove that CAS and tasks run twice.
Implement a lock-free stack with push and pop using compare-and-swap on the head pointer. What correctness concerns do you have, and how does the language runtime change them?
Sample Answer
Direct answer
A lock-free stack (a Treiber stack) keeps one shared head pointer. Push sets the new node's next to the current head, then uses compare-and-swap (CAS), an atomic instruction that writes a new value only if the location still holds the value you expected, to swing head to the new node; if the CAS fails, another thread got in first, so reload and retry. Pop reads head and head->next, then CASes head from the old top to that next. The correctness concerns are the ABA problem (a CAS succeeds because the head looks unchanged although it was popped and pushed back in between), memory reclamation (freeing a node another thread may still read), memory ordering, and CAS retry cost under contention. A garbage collector (GC), the runtime feature that frees unreachable objects automatically, removes the reclamation concern and the pointer-reuse form of ABA, so the concerns that remain depend on whether the runtime frees memory for you.
The algorithm in plain steps
push(n): readh = head; storen->next = h;CAS(head, h, n). On failurehis refreshed with the new head and the loop repeats.pop(): readh = head; if it is null the stack is empty; readnx = h->next;CAS(head, h, nx). On success the caller ownsh.- Both operations are lock-free: if some thread's CAS fails, it is because another thread's CAS succeeded, so the system as a whole always makes progress (an individual thread can still lose the race repeatedly).
Correctness concerns
| Concern | What goes wrong | Fix |
|---|---|---|
| ABA | Pop reads top A and A->next = B, stalls. Other threads pop A, pop B, push A back. The head is A again, so the stalled CAS succeeds and installs B, a node that is no longer in the stack. | Start with a version tag packed into the head word (shown below). A double-width CAS (one compare-and-swap on two adjacent machine words, so a full pointer plus a tag fit) does the same for real pointers. Hazard pointers or epochs go further: they keep A from being reused at all while anyone holds it. |
| Reclamation | Pop reads h->next after another thread freed h: a use-after-free, even if the CAS later fails. | Never free to the allocator while readers may exist: pool plus tag, hazard pointers, epoch-based reclamation, or a GC. |
| Memory ordering | The new node's fields must be visible to the thread that pops it. | Push CAS uses release, pop uses acquire, so a popper that sees the new head also sees the node's contents. Release means every write this thread made earlier (here n->next) is visible to any thread whose acquire load sees the value stored. Without the pair, a weakly ordered CPU (one that may make writes visible in a different order from the program order) can show the new head while the node's next still holds old data, and the popper follows garbage. |
| Contention | Every thread retries on the same cache line. | Backoff (wait briefly, longer after each failure, before retrying) is the first step. If profiling shows the head is still hot, change the structure: per-thread stacks, or elimination (a push and a pop that meet in a side slot hand the value to each other without touching head). |
Worked example: ABA caught, then prevented
The program below keeps nodes in a fixed pool and identifies them by index. The head word is (tag << 32) | index: one 64-bit number whose low 32 bits are the index of the top node (NIL, 0xFFFFFFFF, means empty) and whose high 32 bits are a tag, a counter that goes up on every successful push or pop. For example, tag 3 with node 0 on top is (3 << 32) | 0, which is 0x0000000300000000 in hexadecimal. pack(tag, idx) builds such a word, idx_of returns the low half and tag_of the high half. The use_tag switch makes pack store tag 0 every time, which gives an ordinary untagged stack from the same code, so Part A can show the failure and the fix side by side. Part A replays the ABA interleaving by hand on an untagged stack, then on a tagged one. Part B runs four threads that pop and re-push nodes (the recycling workload that provokes ABA) and checks that every node survives exactly once.
// Treiber stack over a fixed node pool. Head = (tag << 32) | index.
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <thread>
#include <vector>
constexpr uint32_t NIL = 0xFFFFFFFFu;
constexpr uint32_t N = 1024; // nodes in the pool
struct Node { std::atomic<uint32_t> next{NIL}; };
static uint64_t pack(uint32_t tag, uint32_t idx) { return (uint64_t(tag) << 32) | idx; }
static uint32_t idx_of(uint64_t h) { return uint32_t(h); }
static uint32_t tag_of(uint64_t h) { return uint32_t(h >> 32); }
struct Stack {
Node nodes[N];
std::atomic<uint64_t> head{pack(0, NIL)};
bool use_tag;
explicit Stack(bool t) : use_tag(t) {}
void push(uint32_t n) {
uint64_t h = head.load(std::memory_order_relaxed);
do {
nodes[n].next.store(idx_of(h), std::memory_order_relaxed);
} while (!head.compare_exchange_weak(
h, pack(use_tag ? tag_of(h) + 1 : 0, n),
std::memory_order_release, std::memory_order_relaxed));
}
uint32_t pop() { // returns NIL when empty
uint64_t h = head.load(std::memory_order_acquire);
for (;;) {
if (idx_of(h) == NIL) return NIL;
uint32_t nx = nodes[idx_of(h)].next.load(std::memory_order_relaxed);
if (head.compare_exchange_weak(
h, pack(use_tag ? tag_of(h) + 1 : 0, nx),
std::memory_order_acquire, std::memory_order_acquire))
return idx_of(h) /* h was not changed on success */;
}
}
};
int main() {
// Part A: replay the ABA interleaving by hand on the UNTAGGED stack.
{
Stack s(false);
s.push(2); s.push(1); s.push(0); // stack: 0 -> 1 -> 2
uint64_t seen = s.head.load(); // T1 reads head = node 0 ...
uint32_t seen_next = s.nodes[idx_of(seen)].next.load(); // ... and its next = node 1, then stalls
uint32_t a = s.pop(); // T2 pops node 0
uint32_t b = s.pop(); // T2 pops node 1 (now "owned" by T2, e.g. freed or reused)
s.push(a); // T2 pushes node 0 back: stack is 0 -> 2
bool ok = s.head.compare_exchange_strong(seen, pack(0, seen_next)); // T1 resumes: CAS succeeds
printf("A) untagged CAS succeeded=%d; stack from head:", ok);
for (uint32_t n = idx_of(s.head.load()); n != NIL; n = s.nodes[n].next.load()) printf(" %u", n);
printf(" (node %u is still owned by T2, node %u was lost)\n", b, a);
}
// Part A2: same replay on the TAGGED stack.
{
Stack s(true);
s.push(2); s.push(1); s.push(0);
uint64_t seen = s.head.load();
uint32_t seen_next = s.nodes[idx_of(seen)].next.load();
uint32_t a = s.pop(); (void)s.pop(); s.push(a);
uint32_t old_tag = tag_of(seen);
bool ok = s.head.compare_exchange_strong(seen, pack(old_tag + 1, seen_next));
printf("A2) tagged CAS succeeded=%d (head index is node %u again, but tag moved %u -> %u)\n",
ok, idx_of(s.head.load()), old_tag, tag_of(s.head.load()));
}
// Part B: 4 threads recycle nodes through the tagged stack; every node must survive exactly once.
{
Stack s(true);
for (uint32_t i = 0; i < N; ++i) s.push(i);
std::vector<std::thread> th;
for (int t = 0; t < 4; ++t)
th.emplace_back([&] {
for (int i = 0; i < 200000; ++i) {
uint32_t a = s.pop(), b = s.pop();
if (a != NIL) s.push(a);
if (b != NIL) s.push(b);
}
});
for (auto& x : th) x.join();
std::vector<int> seen(N, 0);
int count = 0;
for (uint32_t n = s.pop(); n != NIL; n = s.pop()) { ++seen[n]; ++count; }
bool dup = false;
for (int c : seen) dup |= c != 1;
printf("B) tagged stack after 4x200000 pop/push rounds: %d nodes remain (expected %u), duplicates_or_missing=%d\n",
count, N, dup);
}
}
Compile and run: g++ -std=c++20 -O1 -g -Wall -Wextra -fsanitize=thread treiber.cpp -o t && ./t (g++ 14.4.0 in a Linux container; ThreadSanitizer (TSan), the compiler's data race detector, printed no warnings, and the same output came from a -O2 build without TSan):
A) untagged CAS succeeded=1; stack from head: 1 2 (node 1 is still owned by T2, node 0 was lost)
A2) tagged CAS succeeded=0 (head index is node 0 again, but tag moved 3 -> 6)
B) tagged stack after 4x200000 pop/push rounds: 1024 nodes remain (expected 1024), duplicates_or_missing=0
Reading it: in A the stalled thread's CAS succeeds because the head index matches, and the stack now starts at node 1 (which T2 holds) while node 0 has vanished. In A2 the three pushes raised the tag to 3 and the pop, pop, push raised it to 6, so the same index no longer matches and the CAS fails, which is the correct outcome. The tag turns "same address" into "same address and same version".
How the language runtime changes the concerns
- C and C++ (no GC). You own reclamation. The pooled-index design above sidesteps freeing but needs the tag; with real pointers you need hazard pointers (each thread publishes the node it is about to dereference, and a node is freed only when nobody has published it) or epoch-based reclamation (nodes are freed once every thread has moved past the epoch in which they were unlinked). Tagged pointers also need a 64-bit atomic on a 32-bit target or a double-width CAS, so check
std::atomic<T>::is_lock_free()for the type you use. - Java with
AtomicReference. Nodes are garbage-collected objects, so a node cannot be freed and its memory reused while any thread still holds a reference to it. That removes use-after-free and the reuse form of ABA as long as every push allocates a fresh node. The loop is the same, just without tags:
import java.util.concurrent.atomic.AtomicReference;
public class TreiberStack<T> {
private static final class Node<T> {
final T item; Node<T> next;
Node(T item) { this.item = item; }
}
private final AtomicReference<Node<T>> head = new AtomicReference<>();
public void push(T item) {
Node<T> n = new Node<>(item), h;
do { h = head.get(); n.next = h; } while (!head.compareAndSet(h, n));
}
public T pop() {
Node<T> h;
do { h = head.get(); if (h == null) return null; } while (!head.compareAndSet(h, h.next));
return h.item;
}
public static void main(String[] args) throws Exception {
TreiberStack<Integer> s = new TreiberStack<>();
Thread[] ts = new Thread[4];
for (int t = 0; t < ts.length; t++) {
ts[t] = new Thread(() -> { for (int i = 0; i < 100_000; i++) s.push(i); });
ts[t].start();
}
for (Thread t : ts) t.join();
long sum = 0, n = 0;
for (Integer v = s.pop(); v != null; v = s.pop()) { sum += v; n++; }
System.out.println("popped " + n + " items, sum " + sum);
}
}
java TreiberStack.java (JDK 21; four threads push 100,000 numbers each, then one thread drains the stack) printed:
popped 400000 items, sum 19999800000
The expected sum is 4 x (0 + 1 + ... + 99,999) = 4 x 4,999,950,000 = 19,999,800,000. ABA returns if you recycle node objects yourself (an object pool) or compare values that can repeat; then AtomicStampedReference, which succeeds only if both the reference and an integer stamp match, is the Java tool.
CAS versus a mutex
A mutex-protected stack is simpler and, uncontended, about as fast. Differences that matter: a thread holding a mutex can be descheduled and stall everyone (lock-free code cannot be blocked by a preempted thread); mutex waiters sleep and wake through the kernel, CAS losers spin and burn CPU and cache bandwidth; the mutex gives no fairness guarantee in general, and CAS gives none per thread (a loser can retry indefinitely), only system-wide progress. Cost per operation is O(1) uncontended in both; the CAS retry count has no fixed upper bound under contention. My recommendation: start with a mutex and a plain stack, and move to the lock-free version only when profiling shows lock contention or when blocking is forbidden (real-time threads, interrupt context).
Using the stack from interrupt handlers
An interrupt service routine (ISR) cannot wait on a mutex held by the code it interrupted: on one core the holder cannot run until the ISR returns, so it deadlocks. A CAS loop works because a higher-priority ISR that preempts a lower one mid-loop only makes the victim's CAS fail once and retry. There is no GC and no malloc in an ISR, so nodes come from a static pool like the one above, and ABA is realistic because a small pool recycles nodes immediately, so keep the tag (a 16-bit index and 16-bit tag fit one 32-bit word; a 16-bit tag wraps after 65,536 updates, so check that against how many updates can happen while one context is preempted). Before relying on it, confirm the target core really has atomic read-modify-write instructions: if is_lock_free() is false the library falls back to something that is not lock-free. This was run on the host only; no microcontroller code was executed.
Pitfalls
- A tag only makes ABA improbable: a 32-bit tag wraps after 2^32 updates of the same word.
- Reading
h->nextbefore the CAS is only safe because the pool never returns memory; with realdeleteit needs hazard pointers or epochs. - Pop must read
nextbefore the CAS, not after, because after a successful pop the node belongs to the caller. - Relaxed ordering on the head CAS can publish a node whose fields the popper cannot yet see.
Unlock Full Question Bank
Get access to all 10 Concurrency, Synchronization & Deadlock interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.