Maps to: Stanford CS149 Fall 2025, Lecture 16 (Nov 20), slide deck
16_finegrainedlock(66 slides). Slides 15–31 of this deck, on implementing locks (test-and-set, TTAS, ticket, CAS, LL/SC), are taught in Lecture 15 §7. This lecture covers the rest: deadlock and its relatives, using locks on a shared data structure, and lock-free data structures. Sources: the public Fall 2025 slides; E. G. Coffman, M. Elphick, A. Shoshani, “System Deadlocks” (Computing Surveys, 1971); S. Heller et al., “A Lazy Concurrent List-Based Set Algorithm” (OPODIS 2005); R. K. Treiber, “Systems Programming: Coping with Parallelism” (IBM RJ 5118, 1986); M. M. Michael, “Hazard Pointers: Safe Memory Reclamation for Lock-Free Objects” (IEEE TPDS, 2004); T. L. Harris, “A Pragmatic Implementation of Non-Blocking Linked-Lists” (DISC 2001); M. Herlihy, N. Shavit, The Art of Multiprocessor Programming (2nd ed.). Every experiment and number below was written for these notes and run on the author’s machine (Apple M4 Pro; clang 21, macOS 27). Other heavy programs were running during many of the timings, so they vary by up to 4× between runs; the notes quote ranges and rely only on what held in every run. Code:code/lecture16/. Reading time: ~80 minutes for the prose; ~15 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Define deadlock (死锁), livelock (活锁) and starvation (饥饿). State the four necessary conditions for deadlock, and fix a deadlock by breaking one of them.
- Explain why a data structure protected by one global lock (全局锁) is correct but serial. Implement hand-over-hand (逐节点交替加锁) locking on a linked list, and explain why it is deadlock-free and what it costs.
- Explain the difference between blocking (阻塞) and lock-free (无锁) algorithms, and what lock-freedom guarantees.
- Implement a single-producer/single-consumer queue with no locks, and state the memory orders it needs.
- Implement a compare-and-swap (CAS) stack. Explain the ABA problem (ABA 问题) step by step, and fix it with a tag or counter.
- Explain why lock-free code cannot simply
freea node, and how hazard pointers (危险指针) solve it, including the re-check the simple version forgets. - Judge when lock-free code is worth it, and when a good lock is faster.
0.2 Prerequisites and scope
- Prerequisites:
- Lecture 15: memory orders, atomics, CAS, how locks are built.
- Lecture 14: coherence traffic, false sharing.
- Lecture 5 and PA2: threads, mutexes, work queues.
- Scope: how to use locks and atomics to build shared data structures. Transactional memory, the next step up in abstraction, is Lectures 17–18.
0.3 Section → code map
| Section | Idea | Demo in code/lecture16/ |
|---|---|---|
| §1 | deadlock, livelock, starvation, the four conditions | 01_deadlock.py (uses lockworld.py), 02_deadlock_real |
| §2 | a shared sorted list: no lock, global lock, hand-over-hand, lazy | 03_linked_list |
| §3.2 | the single-producer/single-consumer queue | 04_spsc_queue |
| §3.3–§3.5 | the CAS stack, ABA, hazard pointers | 05_aba.py (uses lockfree.py), 06_treiber |
Run them all with cd code/lecture16 && make run (~10 seconds).
0.4 Notation
- T0, T1, …: threads. Critical section (临界区): code that must not run in two threads at once.
- Wait-for graph (等待图): an edge T_i → T_j means T_i waits for something T_j holds.
- CAS(addr, expected, new): atomically, if
*addr == expectedthen*addr = new. It reports success, or returns the old value. - Node A, B, … in §3 are node addresses, not values (slide 55’s warning).
1. Deadlock, livelock, starvation (slides 3–13)
1.1 Three ways for progress to stop (slides 3–6, 12–13)
- Deadlock (slide 4): the system has outstanding operations to complete, and no operation can make progress. It typically happens when each operation has acquired a resource that another one needs. No thread can proceed unless some thread gives up a resource (“backs up”). Gridlock at a four-way intersection is the picture: every car holds its square and wants the next.
- Livelock (slide 12): the system is executing many operations, but no thread makes meaningful progress. The everyday example is two people in a corridor who keep stepping aside the same way. In computer systems, operations continually abort and retry.
- Starvation (slide 13): the system as a whole makes progress, but some thread does not. For example, cars on one road must always yield to the other road. It is a fairness problem, usually not permanent.
Deadlock and livelock are correctness problems; starvation is a fairness problem.
1.2 Deadlock in computer systems (slide 7)
Two examples from slide 7:
- Work queues. Thread A produces work into B’s queue and B into A’s. The queues are bounded and producers wait when the queue is full. If both queues fill up, each thread waits for space the other must make.
- A message ring. Every thread does a blocking send to thread id + 1, then receives from thread id − 1. If a send blocks until the message is received, every thread is stuck in its send.
1.3 The four conditions (slide 8)
Deadlock requires all four of the following (Coffman et al., 1971):
- Mutual exclusion: a resource can be held by only one thread at a time.
- Hold and wait: a thread holds resources while it waits for others.
- No preemption: resources are released only voluntarily, when the holder is done.
- Circular wait: the waiting relationships form a cycle in the resource dependency graph.
Break any one, and deadlock is impossible. Demo 01 runs this in lockworld.py, a deterministic world in which each thread is a small program of lock operations, executed one step at a time. Two threads take locks A and B in opposite orders:
T0: lock A
T1: lock B
T0: work
T1: work
T0: lock B -> blocked (held by T1)
T1: lock A -> blocked (held by T0)
deadlock wait-for cycle: T0 waits for T1 (B) -> T1 waits for T0 (A)
Then the same program with one condition removed at a time:
| change | breaks condition | outcome |
|---|---|---|
| both threads lock A before B (a global lock order) | 4, circular wait | finished |
| take both locks in one step, or block holding none | 2, hold and wait | finished |
trylock the second; if busy, release the first and retry | 3, no preemption (given up voluntarily) | livelock |
| … plus different back-off delays (1 vs. 2 steps) | 3 | finished |
| … plus randomized exponential back-off | 3 | finished |
The third row is instructive. Breaking deadlock by backing off creates livelock when the threads move in lock-step: both take their first lock, both fail on the second, both release, both retry, forever. Asymmetry breaks it, and randomization is the standard way to get asymmetry, as in Ethernet’s collision back-off.
The other examples behave the same way:
- Slide 7’s message ring (4 threads, unbuffered channels) deadlocks with the cycle T0 → T1 → T2 → T3 → T0. Two fixes work: letting odd threads receive first, or giving each channel one slot of buffering.
- Dining philosophers (5 threads, each picking up the left fork, then the right) deadlocks in a 5-cycle. Taking the lower-numbered fork first, a global order, fixes it.
- Starvation, 3 threads, one lock, 90 steps: an unfair lock that always grants the lowest-numbered waiter gave the threads 11, 11 and 0 critical sections. A FIFO lock gave 8, 7, 7.
1.4 Real deadlocks are silent
Demo 02 creates the opposite-order deadlock with real threads and std::timed_mutex. Each thread holds its first lock and waits up to 500 ms for the second. Neither thread would ever report a problem by itself. Only the time-out reveals it, and the first time-out breaks the cycle: the thread that gives up releases its lock, and the other thread then gets both. A time-out is a form of preemption. Databases and some kernels use time-outs or periodic wait-for-graph checks for exactly this reason. This is deadlock detection and recovery, the alternative to prevention.
The two standard preventions, measured on 400,000 transfers between two accounts in opposite directions:
- A global lock order. Lock the lower address first.
std::scoped_lock(a, b). It takes several locks in any order without deadlock: it locks one, tries the others, and backs off on failure.
Both cost 11–17 ns per transfer, and both conserved the money. But every call site must use them. One plain lock_guard pair in the wrong order brings the deadlock back. In other words, locks do not compose, which is Lecture 17’s motivation for transactions.
2. Using locks: a shared sorted linked list (slides 32–47)
2.1 What goes wrong without synchronization (slides 33–36)
Slide 33’s sorted list inserts by walking to the first node larger than the new value and linking the new node in front of it.
- Two concurrent inserts. Thread 1 inserts 6 and thread 2 inserts 7, at the same place. Both compute the same
prevandcur; each setsprev->nextto its new node, and the later write wins. One insertion is lost (slide 35). - An insert concurrent with a delete. The new node can end up attached to a node that is no longer in the list (slide 36).
Demo 03 runs 4 threads that each insert 2,000 distinct keys into one list without synchronization. insert reported success 8,000 times. Across runs, the list then held 91–418 fewer nodes. In some runs the list was not even sorted any more. On a weakly ordered machine, another thread can see a new node linked in before it sees the node’s own fields: Lecture 15’s message-passing problem.
2.2 Solution 1: one lock for the whole list (slides 37–38)
Wrap every operation in lock(list->lock) … unlock(list->lock).
- Good: it is simple to get correct mutual exclusion.
- Bad: every operation on the list is serialized, which may limit the whole application’s performance.
2.3 Solution 2: hand-over-hand locking (slides 39–45)
Give every node its own lock and traverse like a climber who never lets go with both hands. Hold the locks on prev and cur; to advance, lock the next node, then release the oldest:
lock(prev = head); lock(cur = prev->next);
while (cur && cur->value < v) {
old = prev; prev = cur; cur = cur->next;
unlock(old); if (cur) lock(cur);
}
// prev and cur are both locked: link a new node between them, or unlink cur
Operations on different parts of the list can proceed in parallel. Slide 46 lists the questions to ask:
- Is it deadlock-free? Yes, by a property you can see at once: every thread acquires locks in list order, front to back. That is a global lock order, so no circular wait.
- Is freeing a deleted node safe? Yes. To wait for
cur’s lock, a thread must holdprev’s lock, which the deleter holds. - What does it cost? A lock acquisition and release at every step of a traversal, which turns each traversal into a sequence of memory writes, plus a lock per node of storage. Threads also cannot overtake each other.
2.4 How they compare on real cores
Demo 03 runs random operations on lists of about 1,000 nodes (and about 32), on 1–8 threads, and checks every list afterwards. It also includes a fourth design, discussed in §2.5. Operations per microsecond, ranges across runs:
| ~1000 nodes | 1 thread | 8 threads |
|---|---|---|
| 50% inserts, 50% deletes | ||
| global lock | 2.3–2.5 | 0.47–0.53 |
| hand-over-hand | 1.7–2.1 | 0.15–0.18 |
| lazy list (§2.5) | 1.5 | 2.1–2.3 |
| 90% lookups, 5% inserts, 5% deletes | ||
| global lock | 2.2–2.3 | 0.9–1.0 |
| hand-over-hand | 2.1 | 0.16–0.31 |
| lazy list | 1.4–1.6 | 7.4–8.4 |
Four lessons:
- The global lock gets slower with more threads, not just flat. The lock, and every list node it protects, moves from core to core with each operation.
- Hand-over-hand was 3–9× slower than the global lock as soon as two threads ran. Every step of every traversal is an atomic read-modify-write on a node’s lock. With several threads walking the same nodes, each step is a coherence miss (Lecture 14’s ~40–90 ns). Our first node lock never yielded the core, and then hand-over-hand nearly stopped (up to 17× slower) whenever a thread holding locks was descheduled: everyone behind it spun on a core it needed. Fine-grained locking is “tricky to ensure correctness” (slide 46), and here it was also slow.
- With 50% updates, nothing scaled well. Even the best design at 8 threads only matched one thread with one lock. Every update invalidates lines that all other traversers read. Fine-grained locking removes the lock bottleneck, not the coherence bottleneck.
- Read-mostly workloads are where fine-grained designs pay off. The lazy list’s lookups take no lock at all, and at 8 threads it ran 3–4× faster than one thread with the global lock.
2.5 A better middle ground (slide 46’s question)
Slide 46 asks for “a middle-ground solution that trades off some parallelism for reduced overhead”. One answer is to lock groups of nodes (an exercise). Demo 03 implements a better-known answer, the lazy list (Heller et al., 2005):
- Traverse without locks. Then lock only
prevandcur, and validate that neither has been deleted meanwhile and thatprevstill points tocur. If validation fails, unlock and retry. - Delete in two steps: first mark
curas deleted (a logical delete), then unlink it. A thread that is already standing on a deleted node can still follow itsnextpointer. - Lookups take no lock: walk, then check the node is not marked. They are wait-free (无等待): they finish in a bounded number of steps whatever other threads do.
The price is subtlety. The memory orders matter: a new node must be fully built before the release store that links it in. And a deleted node cannot be freed right away, because a lock-free traversal might be standing on it. Demo 03 keeps unlinked nodes until all threads finish. Real code needs safe memory reclamation, the topic of §3.4.
3. Lock-free data structures (slides 48–64)
3.1 Blocking vs. lock-free (slides 49–50)
A blocking algorithm lets one thread prevent other threads from completing operations indefinitely (slide 49). Suppose thread 0 holds a lock on a list node and is then descheduled by the OS, takes a page fault, crashes, or is just slow. No other thread can complete operations on that part of the structure, although thread 0 is not making progress either. Any algorithm that uses locks is blocking, whether the locks spin or sleep.
An algorithm is lock-free if some thread is always guaranteed to make progress (“system-wide progress”, slide 50). Preempting one thread at an inopportune moment cannot stop the rest of the system. Lock-freedom does not prevent starvation of an individual thread: a thread whose compare-and-swap keeps failing may retry forever while others succeed. The stronger guarantee that every thread finishes in a bounded number of its own steps is called wait-free. The lazy list’s lookup in §2.5 is an example.
3.2 A single-producer, single-consumer queue (slides 51–53)
With exactly one producer and one consumer, a bounded ring buffer needs no lock at all (slide 51). The producer is the only writer of tail, the consumer the only writer of head:
bool push(Queue* q, int v) { // producer only
if (q->tail == MOD_N(q->head - 1)) return false; // full
q->data[q->tail] = v;
q->tail = MOD_N(q->tail + 1); // publish
return true;
}
bool pop(Queue* q, int* v) { // consumer only
if (q->head == q->tail) return false; // empty
*v = q->data[q->head];
q->head = MOD_N(q->head + 1); // free the slot
return true;
}
Threads never wait for each other: a push to a full queue or a pop from an empty one simply fails. The slide adds a footnote: “assume a sequentially consistent memory system (or the presence of appropriate memory fences, or C++11 atomic<>)”. The footnote is essential. “Write the slot, then publish tail” is Lecture 15’s message-passing pattern, once per item:
- the producer’s store of
tailmust be a release; - the consumer’s load of
tailmust be an acquire; - symmetrically, the consumer releases
headafter reading the slot, and the producer acquires it.
Demo 04 pushes the sequence 1, 2, 3, … through a 1,024-slot ring, 2 million items, best of 3 runs. The consumer checks every value:
| version | ns per item | out-of-sequence values seen |
|---|---|---|
| a mutex around every push and pop | 62–155 | 0 |
| slide 51 with release/acquire (head and tail in one cache line) | 22–51 | 0 |
| the same with relaxed atomics | 4–8 | 0–6 per run |
| release/acquire + head and tail on separate lines + cached copies | 3.3–7.4 | 0 |
The relaxed version really does read slots before their contents arrive, on this weakly ordered machine. It is rare (a handful of times in 6 million items), which makes it all the more dangerous.
The last row matters too. Slide 51’s version keeps head and tail side by side, so every push and pop touches a line the other core is writing. Two changes cut the cost 3–15×:
- put the two indices on separate 128-byte lines (Lecture 14);
- let each side keep a private copy of the other side’s index, and re-read the shared one only when its copy says “full” (producer) or “empty” (consumer).
Lock-free is not automatically fast; coherence decides.
The unbounded version (slides 52–53, from Dr. Dobb’s Journal) uses a linked list with a dummy node. It has a nice trick for memory: all allocation and freeing is done by the producer. A reclaim pointer trails behind head, and the producer deletes the nodes the consumer has passed, so the two threads never race on delete.
3.3 A lock-free stack, and the ABA problem (slides 54–57)
Treiber’s stack (slide 54) has one shared word, top:
void push(Stack* s, Node* n) {
while (1) {
Node* old_top = s->top;
n->next = old_top;
if (compare_and_swap(&s->top, old_top, n) == old_top) return;
}
}
Node* pop(Stack* s) {
while (1) {
Node* old_top = s->top;
if (old_top == NULL) return NULL;
Node* new_top = old_top->next;
if (compare_and_swap(&s->top, old_top, new_top) == old_top) return old_top;
}
}
“As long as no other thread has modified the stack, a thread’s modification can proceed”. If another thread changed top, the CAS fails and we retry. Unlike fine-grained locking, no thread ever holds a lock on any part of the structure.
But the CAS checks only that top has the same value. It does not check that nothing happened. Slide 55’s interleaving, as demo 05 prints it, with the stack initially A → B → C:
T0 pop: read top = A
T0 pop: read A.next = B <- T0 is paused here
T1 pop: read top = A
T1 pop: read A.next = B
T1 pop: CAS top A -> B succeeds, returns A
T1 push(D): read top = B
T1 push(D): CAS top B -> D succeeds
T1 push(A): read top = D <- T1 reuses node A
T1 push(A): CAS top D -> A succeeds
T0 pop: CAS top A -> B succeeds, returns A <- top "is still A", so the stale new_top = B goes in
final stack: B -> C node D is lost
This is the ABA problem. The value went A → D → A, and the CAS could not tell that anything had happened in between.
The fix (slide 56): keep a pop counter next to top, and compare-and-swap the pair (top, pop_count) as one unit. Every pop changes the pair even when the same node comes back to the top, so a CAS based on a stale read always fails. Two variants of the instruction exist:
- a “double compare-and-swap” of two separate words, which few machines have;
- a CAS of one double-width word. x86 has
cmpxchg8bandcmpxchg16b(slide 57), ARM hascasp. Or pack a small index and a tag into one 64-bit word, as demo 06 does.
Demo 05 then runs every possible interleaving of the same two threads, with each shared-memory access as one step:
| stack | interleavings | lose a node |
|---|---|---|
| plain CAS (slide 54) | 58,184 | 63 |
| CAS on (top, pop count) (slide 56) | 58,265 | 0 |
Only about 1 in 1,000 interleavings fails, which is why testing rarely finds ABA. Exhaustive exploration finds every one.
On real hardware. Demo 06 runs a Treiber stack on a pool of 8 constantly reused nodes. Each thread pops a node, marks it owned, works ~20 ns, unmarks it, and pushes it back. Nodes are named by 32-bit indices, and the 64-bit top word is index | tag << 32. Across runs, the untagged stack:
- was correct on 1 and 2 threads;
- at 4–8 threads, broke in 3 of 4 runs without any help: hundreds of thousands of nodes handed to two threads at once, and the stack’s next pointers looping into a cycle.
A version with the read-to-CAS window artificially widened to ~100 ns broke every time. The tagged stack was never corrupted.
3.4 Freeing nodes: use-after-free and hazard pointers (slides 58–59)
A real stack also frees the nodes it pops (slide 58). Now a new problem appears. Thread 0 reads old.top = A and is about to read A->next. Meanwhile thread 1 pops A and deletes it. Thread 0 then reads freed memory. That is undefined behaviour, a crash, or garbage that a later CAS installs into the stack.
Hazard pointers (slide 59; M. Michael, 2004):
- Each thread publishes, in a per-thread “hazard” slot, the node it is about to dereference.
- A thread that pops a node does not delete it. It retires it to a per-thread list.
- From time to time, the thread deletes the retired nodes that no thread’s hazard pointer points to.
Demo 05 explores every interleaving of two threads that each pop and free one node:
| protection | interleavings | use-after-free |
|---|---|---|
| none | 2,598 | 54 |
slide 59’s old.top = hazard = s->top | 13,528 | 88 |
| publish the hazard, then re-read top and retry if it changed | 60,610 | 0 |
Slide 59’s one-line version still fails, and exhaustive search shows exactly how:
T0 pop: read top = A
T0 pop: hazard = A
T0 pop: read A.next = B
T1 pop: read top = A <- T1 has read top, but not yet published its hazard
T0 pop: CAS top A -> B succeeds
T0 frees A <- nobody's hazard points to A yet
T1 pop: hazard = A <- too late
T1 pop: read A.next -> use-after-free
Reading top and publishing the hazard are two separate steps. A node can be popped and freed in between. Michael’s protocol therefore re-reads top after publishing the hazard, and proceeds only if it is unchanged. Then the node was still on the stack after the hazard became visible, so no thread can have freed it. (The slide labels itself an “advanced topic” sketch. The demo shows why the full protocol has its extra step.) Other reclamation schemes include epoch-based reclamation, reference counting, and RCU (read-copy-update) in the Linux kernel.
3.5 Lock-free linked lists, and whether lock-free is worth it (slides 60–64)
Linked lists. Inserting into a lock-free list is a CAS on prev->next (slide 60), with no locks and no per-node lock storage. Deletion is much harder (slide 61). Suppose B is being deleted (CAS A.next: B → C) while E is inserted after B (CAS B.next: C → E). Both CASes succeed, and E hangs off a node that is no longer in the list. Harris (2001) solves it by marking the next pointer of a node being deleted (stealing a low bit of the pointer), so that a concurrent CAS on B.next fails. This is the lock-free cousin of the lazy list’s marked flag.
Performance. Slide 62 (Hunt 2011) shows lock-free queues, lists and deques sometimes beating locks and sometimes not. Demo 06 on the author’s machine:
| pop + push per µs | 1 thread | 8 threads |
|---|---|---|
std::mutex stack | 24–106 | 18–45 |
| lock-free, tagged | 44–164 | 2.7–15 |
On one thread, lock-free was 1.3–4× faster: one CAS instead of a lock and an unlock. On 8 threads the mutex was 1.2–17× faster, usually more than 10×. Lock-free does not eliminate contention (slide 64): every operation still fights for the same top line, and failed CASes reached about 7 per successful operation, while the mutex lets waiters sleep instead of competing.
When is lock-free worth it (slide 63)? When you control the machine and only your program runs, which is the usual assumption of this course, well-written lock-based code is often as fast and much simpler. Lock-free designs earn their complexity in systems with many threads, preemption, page faults and failures: databases, web servers, operating system kernels. There, locks cause:
- priority inversion: a low-priority lock holder blocks a high-priority thread;
- convoying: everyone queues behind a descheduled holder, as with demo 03’s spinning hand-over-hand;
- crashes inside critical sections, which leave the lock held.
Lock-free code still needs the right memory orders on relaxed hardware (slide 64), as demo 04’s relaxed queue showed.
3.6 Preview: what was the CAS for? (slide 65)
In every lock-free structure above, the CAS detected whether another thread had modified the data structure while this thread was in the middle of an operation. If not, the change was committed; otherwise it was retried. Transactional memory generalizes exactly that: let any block of code run speculatively, detect conflicting modifications, and abort and retry if one happened.
Summary
- Deadlock needs mutual exclusion, hold-and-wait, no preemption and circular wait at once. A global lock order (no circular wait) is the cheapest prevention. Back-off-and-retry breaks deadlock but can livelock in lock-step, and randomization breaks the symmetry. Starvation is unfairness: an unfair lock gave one thread 0 of 22 critical sections. Real deadlocks are silent; detect them with time-outs or wait-for graphs.
- A global lock is simple and correct, and serial. Hand-over-hand locking is deadlock-free (locks taken in list order) and allows parallel operations, but costs a lock at every traversal step. On the author’s machine it was 3–9× slower than the global lock. The lazy list traverses without locks, locks and validates only two nodes, and has wait-free lookups. It scaled to 3–4× a single thread on a read-mostly workload. Update-heavy workloads did not scale with any design, because updates cause coherence traffic.
- Lock-free means some thread always makes progress; wait-free means every thread does. A single-producer single-consumer queue needs no lock, but needs release/acquire. A relaxed version really failed on arm64. Padding and cached indices made the correct version 3–15× faster.
- The CAS stack suffers ABA: a stale CAS succeeds because the pointer came back. Tagging the top with a pop counter fixes it. The bug appeared in about 1 in 1,000 interleavings in the model, and in most real 4–8-thread runs. Freeing nodes needs safe reclamation: hazard pointers, with the re-check after publishing.
- Lock-free is not automatically faster. Under contention the mutex stack was usually over 10× faster. Choose lock-free for robustness against preemption and failures, or for low contention, not by default.
Common pitfalls
- Acquiring locks in different orders in different functions. Pick a global order (by address, by level) and document it; or use
std::scoped_lock, at every call site. - “Fixing” deadlock with try-lock and immediate retry. In lock-step this livelocks. Back off by a random, growing delay.
- Assuming fine-grained locking is faster. Measure. A lock per traversal step can be slower than one lock for everything.
- Spinning node locks that never yield. With more runnable threads than cores (or other programs running), a descheduled lock holder stalls everyone spinning behind it.
- Forgetting memory orders in lock-free code. Slide 51’s queue “assumes sequential consistency”. With relaxed atomics on ARM the consumer read unwritten slots.
- Trusting a CAS to mean “nothing changed”. It means “the value is the same”. Reused nodes need a tag, or a reclamation scheme that prevents reuse while anyone might still compare against the node.
- Freeing a node as soon as it is unlinked. Another thread traversing without locks may still be on it. Use hazard pointers (publish, then re-check), epochs or RCU.
- Calling a structure “lock-free” when it uses a lock internally.
std::atomic<T>for a large T may be implemented with a lock. Checkis_lock_free().
Exercises
-
Four conditions. A program has a thread pool. Each task locks the input queue’s lock, takes an item, and while still holding it, locks the output queue’s lock to push its result. The output queue’s consumer does the reverse, locking the output lock and then the input lock to recycle buffers. Can it deadlock? Name the conditions, and propose the smallest fix.
Answer
Yes. A task holds the input lock and waits for the output lock, while the consumer holds the output lock and waits for the input lock: mutual exclusion, hold-and-wait, no preemption, and a circular wait of length 2. The smallest fix is a global order: both acquire the input lock before the output lock. Alternatively, do not hold one lock while acquiring the other: release the input lock before pushing the output. -
Livelock. Two threads run
while (1) { lock(A); if (try_lock(B)) break; unlock(A); }(and symmetrically with B then A). Explain why they can make no progress, and give two fixes.Answer
If they run in lock-step, each takes its first lock, fails to try-lock the other's, releases, and retries, forever. That is livelock: they are busy, but nothing completes. Fixes: (1) a global order, so both take A first; then no back-off is needed. (2) Random, increasing back-off before retrying, so that eventually one thread retries while the other is not holding its lock. Demo 01 shows both. -
Why is hand-over-hand deadlock-free? The insert and delete of slide 45 both take two locks at a time. Why can no cycle of waits form?
Answer
Every operation acquires node locks strictly in list order, from the head towards the tail, and never acquires a node's lock while holding the lock of a later node. So locks are always requested in one global order, the position in the list. A wait-for cycle would need some thread to wait for an earlier node while holding a later one, which never happens. -
Slide 45’s challenge: improve
insert(). In hand-over-hand insert, is it necessary to holdcur’s lock while linking in the new node?Answer
No. Holding `prev`'s lock is enough, because any operation that could change the link between prev and cur must hold `prev`'s lock: deleting cur requires locking prev and cur, and inserting between them requires prev. Once insert has found the position, it can release `cur` (or never take the last `cur` lock) and link the node under `prev`'s lock alone. Locking `cur` is needed during traversal only to step forward safely. -
Two producers. Why does slide 51’s ring buffer break with two producers? What is the smallest change that would make push safe for several producers?
Answer
Two producers can read the same `tail`, both write the same slot (one value is lost) and both advance `tail` to the same next index. The single-writer property of `tail` was what made the queue lock-free and correct. Fix: claim a slot with an atomic RMW on `tail` (fetch_add or a CAS loop), then write the slot. The consumer must then also know when a claimed slot's write has finished, for example with a per-slot sequence number, as in Vyukov's bounded multi-producer queue. -
ABA with a tag. In demo 06 the tag is 32 bits and is incremented on every pop. Describe an interleaving in which even the tagged stack suffers ABA. How likely is it?
Answer
Thread T0 reads (top = A, tag = t) and is paused before its CAS. Other threads then perform exactly 2³² pops (plus pushes) so that the tag wraps around to t, with A back on top. T0's CAS succeeds on stale data. That requires about 4 billion operations while T0 is paused, possible only if T0 is descheduled for many seconds under extreme load. With a 64-bit tag (a 128-bit CAS) it is practically impossible. With an 8-bit tag, 256 pops suffice, which is easy (code exercise 6). -
The hazard-pointer re-check. In demo 05, why does
hazard = topfollowed immediately byread top->nextstill allow a use-after-free, and why does re-readingtopfix it?Answer
Between the read of `top` (value A) and the store to the hazard slot, another thread can pop A and scan the hazard slots. It finds no hazard on A, and frees it. The hazard published afterwards protects nothing. If, after publishing, the thread re-reads `top` and finds it still equal to A, then A was still on the stack at a moment when the hazard was already visible. Any thread popping A afterwards will see the hazard and keep A. If `top` changed, the thread retries. -
Lock-free or wait-free? Is Treiber’s stack lock-free? Is it wait-free? What about the lazy list’s
contains?Answer
Lock-free: a CAS fails only because another thread's CAS succeeded, so whenever some thread retries, some other thread has made progress. Not wait-free: an unlucky thread can fail its CAS forever under contention (demo 06 averaged up to ~7 failures per successful operation). The lazy list's `contains` is wait-free: it takes no locks and never retries; it walks at most the length of the list (plus nodes inserted meanwhile) and returns. -
Unbounded SPSC reclamation (slides 52–53). In the unbounded single-producer single-consumer queue, why does the producer free the nodes the consumer has passed, rather than the consumer freeing them as it pops?
Answer
Because then only one thread ever calls `new` and `delete` on queue nodes, and the producer can tell which nodes the consumer has finished with: everything before `head`. If the consumer freed a node right after popping it, the producer might still be using it, for example as `tail`, whose `next` it is about to set. Keeping allocation and freeing in one thread avoids the reclamation race that hazard pointers solve in the general case.
The related assignment
The assignments use locks rather than lock-free structures, and their bugs are exactly §1–§2’s:
- PA2: a thread pool’s task queue and dependency counters are shared data structures. Deadlock appears if a worker waits on a condition while holding a lock another worker needs to signal it. Starvation appears if the queue is unfair.
- PA3 / PA5: GPU code avoids most of this by design (no locks across thread blocks), and CUDA’s
atomicCASis the slide-27 primitive from which the lock-free ideas here are built.
The habits carry over directly:
- one documented lock order;
- the smallest critical sections that are still correct;
- measuring before going fine-grained;
- ThreadSanitizer on every multi-threaded build.
Further reading
- The Fall 2025 slides for this lecture.
- E. G. Coffman, M. J. Elphick, A. Shoshani, “System Deadlocks”, ACM Computing Surveys, 1971: the four conditions.
- M. Herlihy, N. Shavit, V. Luchangco, M. Spear, The Art of Multiprocessor Programming, 2nd ed., 2020. Chapter 9 covers coarse, fine-grained, optimistic, lazy and lock-free lists; chapters 10–11, queues and stacks, including ABA.
- S. Heller, M. Herlihy, V. Luchangco, M. Moir, W. N. Scherer, N. Shavit, “A Lazy Concurrent List-Based Set Algorithm”, OPODIS 2005.
- M. M. Michael, M. L. Scott, “Simple, Fast, and Practical Non-Blocking and Blocking Concurrent Queue Algorithms”, PODC 1996: the multi-reader/writer lock-free queue (slide 66).
- T. L. Harris, “A Pragmatic Implementation of Non-Blocking Linked-Lists”, DISC 2001 (slide 61).
- M. M. Michael, “Hazard Pointers: Safe Memory Reclamation for Lock-Free Objects”, IEEE TPDS, 2004.
- P. E. McKenney, Is Parallel Programming Hard, And, If So, What Can You Do About It? (free online): RCU, deferred reclamation, real-world locking.
Preview of Lecture 17 — Transactional memory (Part I)
Locks gave us correctness at the price of deadlock risk, lost parallelism, and code that does not compose. Lock-free structures gave us progress guarantees at the price of a CAS-shaped algorithm per data structure, ABA and memory-reclamation puzzles. Lecture 17 asks: what if the programmer just wrote atomic { … } around any block of code, and the system made it appear to happen all at once, retrying if it conflicted with another thread? It covers:
- what transactions promise: atomicity, isolation, serializability;
- why they compose where locks do not;
- the two design choices every implementation makes: how to keep old and new data apart (versioning), and when to look for conflicts (detection).
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| deadlock / livelock / starvation | 死锁 / 活锁 / 饥饿 |
| mutual exclusion / hold and wait | 互斥 / 占有并等待 |
| no preemption / circular wait | 不可抢占 / 循环等待 |
| wait-for graph | 等待图 |
| deadlock prevention / avoidance / detection and recovery | 死锁预防 / 避免 / 检测与恢复 |
| lock ordering (global lock order) | 加锁顺序(全局锁序) |
| try-lock / back-off (exponential, randomized) | 尝试加锁 / 退避(指数、随机) |
| time-out | 超时 |
| dining philosophers | 哲学家就餐问题 |
| fairness | 公平性 |
| critical section | 临界区 |
| global (coarse-grained) lock | 全局(粗粒度)锁 |
| fine-grained locking | 细粒度锁 |
| hand-over-hand locking (lock coupling) | 交替加锁(锁耦合) |
| optimistic traversal / validation | 乐观遍历 / 校验 |
| lazy list / logical deletion (marking) | 惰性链表 / 逻辑删除(标记) |
| composability | 可组合性 |
| blocking / non-blocking algorithm | 阻塞 / 非阻塞算法 |
| lock-free / wait-free | 无锁 / 无等待 |
| system-wide progress | 系统级进展 |
| single-producer single-consumer (SPSC) queue | 单生产者单消费者队列 |
| ring buffer (circular buffer) | 环形缓冲区 |
| compare-and-swap (CAS) / double-width CAS | 比较并交换 / 双字宽比较并交换 |
| Treiber stack | Treiber 无锁栈 |
| ABA problem | ABA 问题 |
| tagged pointer / version counter | 带标签指针 / 版本计数器 |
| memory reclamation | 内存回收 |
| use-after-free | 释放后使用 |
| hazard pointer / retire list | 危险指针 / 待回收列表 |
| epoch-based reclamation / RCU | 基于纪元的回收 / 读-复制-更新 |
| priority inversion / convoying | 优先级反转 / 护航效应 |
| contention | 争用 |
| transactional memory | 事务内存 |