Lecture 23 · Synchronization — advanced

Introduction to Computer Systems · Lecture 23。个人学习讲义与配套实验,按主题整理并持续修订。

课程源码 ZIP ↓

个人整理的学习笔记,非官方讲义;课程来源与整理说明见课程介绍。配套示例未逐一运行验证。

本篇目录

Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 23 (Nov 24), slide deck sync-advanced. Reading: CS:APP3e §12.5.4–§12.5.5, §12.7–§12.8. Sources: the public Fall 2026 slides and CS:APP. The code is original to these notes and run on an Apple M4 Pro (12 cores: 8 performance + 4 efficiency), macOS, clang 21. Timings are from one run. Code: code/lecture23/. Reading time: ~90 minutes; ~20 more for the demos.


0. How to read this lecture

0.1 Learning goals

After this lecture you should be able to:

  1. Solve the producer/consumer problem with two counting semaphores plus a mutex, and explain why a mutex alone cannot do it.
  2. Explain why the order of P operations matters, and spot the deadlock that reversing them creates.
  3. Use a readers/writers lock, and decide from measurement — not assumption — whether it pays.
  4. Define starvation and say why readers/writers risks it.
  5. Classify a thread-unsafe function into CS:APP’s four classes and apply the right fix, including why strtok is unsafe and strtok_r is not.
  6. Recognize races a mutex cannot fix (time-of-check/time-of-use).
  7. Diagnose deadlock via the four necessary conditions and prevent it by lock ordering.

0.2 Prerequisites and scope

  • Lecture 22: mutexes, semaphores (P/V), atomics, and the cost of each. This lecture uses all of them.
  • Lecture 21: threads and what they share. Lecture 16: fork (demo 03 needs a disposable child). Lecture 17: SIGKILL.
  • In scope: CS:APP §12.5.4–§12.5.5 (producer/consumer, readers/writers) and §12.7–§12.8 (thread safety, reentrancy, races, deadlock).
  • Out of scope: parallel speedup, cache coherence and memory consistency (Lecture 24).
  • Policy: the proxy lab’s cache is a readers/writers problem. These notes contain no lab solutions — the demos use a bounded buffer and a toy array, with no cache and no proxy.

0.3 Section → code map

SectionIdeaDemo in code/lecture23/
§1producer/consumer, counting semaphores01_producer_consumer.c
§2readers/writers, and when it pays02_readers_writers.c
§3thread safety, the four classes04_thread_safety.c
§4races a lock cannot fix(discussion)
§5deadlock and lock ordering03_deadlock.c

1. Producer/consumer: when a mutex cannot count

1.1 The problem

Producers make items, consumers use them, and a fixed-size buffer sits between them (this is how a thread pool’s work queue, a pipeline stage, and a network server’s request queue all work). Three things must hold simultaneously:

  1. Mutual exclusion — only one thread manipulates the buffer’s internals at a time, or two producers write the same slot.
  2. A consumer must wait while the buffer is empty.
  3. A producer must wait while the buffer is full.

A mutex gives you (1) and nothing else. It has no notion of how many — it cannot express “wait until there is something to take”. This is exactly where counting semaphores earn their existence.

1.2 The solution: two semaphores as counters

Use two semaphores as counters of availability:

SemaphoreInitial valueMeans
items0how many full slots are in the buffer
slotsNhow many empty slots are in the buffer
Producer:  P(slots) → P(mutex) → insert → V(mutex) → V(items)
Consumer:  P(items) → P(mutex) → remove → V(mutex) → V(slots)

The symmetry is the whole solution: each side waits on the resource it consumes and signals the resource it produces. A producer consumes an empty slot and produces an item; a consumer does the reverse. The mutex in the middle protects only the buffer’s bookkeeping.

01_producer_consumer.c runs 3 producers and 3 consumers over an 8-slot buffer, and verifies by invariant rather than by inspection:

  items produced/consumed : 60000 / 60000
  checksum produced       : 1799970000
  checksum consumed       : 1799970000  -> MATCH (nothing lost or duplicated)
  buffer occupancy stayed : 0 .. 8 (capacity 8) -> never overflowed
  final occupancy         : 0 (should be 0)

Each item carries a unique value, so matching checksums prove no item was lost (a consumer reading an empty slot) or duplicated (two consumers taking the same one). The recorded maximum occupancy of exactly 8 shows P(slots) really did block producers when the buffer filled — something a mutex could never arrange.

1.3 Why P(slots) must come before P(mutex)

This ordering is load-bearing, and reversing it is an instructive disaster:

P(mutex);        /* WRONG */
P(slots);        /* wait for a free slot -- while holding the lock! */

A producer now holds the mutex while waiting for a slot. But only a consumer can free a slot, and to do so it must take the mutex — which the blocked producer is holding. Neither can proceed: immediate deadlock.

The general rule, which §5 formalizes: never block on a second resource while holding a lock. Acquire the counting semaphore first (it says whether work is even possible), then the mutex (which you hold only for the few instructions that touch shared state), and release in the reverse order.

1.4 Termination

One wrinkle every real pipeline faces: a consumer blocked in P(items) when no more items will ever come waits forever. The demo sidesteps it by telling consumers exactly how many items to take. Real designs use a sentinel (“poison pill”) item per consumer, or a shutdown flag checked under the mutex, or a semaphore with a timeout. Deciding how a pipeline ends is part of designing it.


2. Readers/writers: when a mutex is too strict

2.1 The problem and the rule

Many threads read a shared structure; a few occasionally write it. A mutex works, but is needlessly strict: it admits one reader at a time, although readers do not interfere with one another at all. The correct rule:

  • any number of readers may hold the lock together;
  • a writer must hold it alone — no readers, no other writer.

That is a readers/writers lock: pthread_rwlock_rdlock (shared) and pthread_rwlock_wrlock (exclusive).

2.2 Does it pay? Measure.

02_readers_writers.c runs 8 readers and 2 writers, and — importantly — measures two different critical-section lengths:

critical sectionmutexrwlockmax readers inside (mutex / rwlock)result
short (1 pass over 64 elements)27 ms34 ms1 / 5rwlock 0.79× — slower
long (100 passes)415 ms64 ms1 / 8rwlock 6.47× faster

Both facts matter.

The mechanism works as advertised. The mutex never let more than 1 reader inside; the rwlock let up to 8 (= all the readers) overlap. And neither produced a single torn read — the demo checks a structural invariant (every element equal), so a reader that saw a half-finished write would be counted, and the count is 0 in all four configurations. Writers kept exclusive access; correctness was never traded for the speedup.

But concurrency is not speed. With a short critical section the rwlock was slower than the mutex. The reason is concrete: an rwlock must atomically maintain a reader count, and that bookkeeping is itself a contended shared variable (Lecture 22’s lesson, one level up). When the work inside the lock is a few hundred nanoseconds, the overhead swamps the benefit. Only when readers stay inside long enough is there enough overlap to amortize the cost — and then the win is large.

So the rule is not “reads dominate → use an rwlock”. It is: reads dominate and the critical section is long enough to pay for the extra bookkeeping. Measure; do not assume.

2.3 Starvation

Readers/writers introduces a hazard mutual exclusion does not have. Starvation is a thread that never gets its turn although the system makes progress:

  • A reader-preferring implementation lets a new reader in whenever any reader holds the lock. If readers keep arriving, a waiting writer may never get in.
  • A writer-preferring implementation makes new readers wait as soon as a writer is waiting. Now a stream of writers can starve the readers.

Neither is “fair” by default, and POSIX does not specify which you get — so do not assume. Fair variants exist (queue the waiters in arrival order) at some extra cost. Starvation differs from deadlock: in deadlock nobody progresses; in starvation the system progresses but one participant is perpetually passed over.


3. Thread safety

A function is thread-safe if it always behaves correctly when called concurrently from multiple threads. CS:APP sorts the unsafe ones into four classes, each with its own fix:

ClassProblemFix
1does not protect shared variablesadd a lock around the accesses
2keeps state across calls in static storagechange the interface: pass the state in
3returns a pointer to a static bufferlock-and-copy, or use the _r variant
4calls a class 1–3 functioninherits the problem; fix the callee or lock the call

3.1 Class 2, measured: strtok

strtok is the canonical Class 2 offender: it remembers where it stopped in a static variable, so two threads tokenizing two different strings destroy each other’s position. 04_thread_safety.c gives 8 threads their own private buffers and counts wrong answers:

  function                            calls        wrong       rate
  strtok    (Class 2, unsafe)         16000        12563     78.52%
  strtok_r  (reentrant, safe)         16000            0      0.00%

78.5% wrong, although no thread shared a string with any other. The shared thing was inside strtok. The fix is strtok_r, where the caller supplies the state:

char *saveptr = NULL;                       /* OUR state, on OUR stack */
for (char *t = strtok_r(buf, " ", &saveptr); t; t = strtok_r(NULL, " ", &saveptr))

Note that a lock cannot fix Class 2. The state must persist between calls, so holding a lock for the duration of one strtok call protects nothing; you would have to hold it across the entire tokenization loop, which serializes the work and is easy to get wrong. The interface itself has to change — which is precisely why the _r (“reentrant”) variants exist.

A near-miss worth recording. The first version of this demo, without a sched_yield() between calls, failed only 1 time in 16 000 (0.01%). That looked like evidence strtok was safe here. It is not: a separate experiment with yields produced 80.9% failures, proving the state really is shared — the original rate was low only because back-to-back strtok calls are too fast to hit the window. Both loops now yield identically, so the comparison stays fair. The same broken code would pass almost any test suite and fail under load. That is what makes Class 2 dangerous, and why you classify functions by reading them rather than by testing them.

3.2 Functions to know

  • Class 2: strtok → strtok_r; rand/srand → rand_r.
  • Class 3 (static return buffer): ctime, localtime, asctime → ctime_r, localtime_r; inet_ntoa; gethostbyname → getaddrinfo (Lecture 19, which is thread-safe and IPv6-capable — one of several reasons it replaced the old API).
  • Reentrant functions — those that access no shared state at all — are automatically thread-safe, and are the cleanest category to aim for. The preference order for any new code: share no state → pass the state in → lock and copy.

4. Races a lock cannot fix

Mutual exclusion solves “two threads touching one variable”. It does not solve problems where the logic assumes nothing changed between two moments.

The classic shape is time-of-check to time-of-use (TOCTOU):

if (access(path, W_OK) == 0) {       /* check: may I write it? */
    /* ... window ... */
    fd = open(path, O_WRONLY);       /* use: write it */
}

Each call may be individually atomic, and the file can still be replaced in the window between them — so the thing you checked is not the thing you used. Locking access and open separately changes nothing, because the shared state (the file system) is outside your locks entirely. The fixes are structural: perform one operation that both checks and acts (open with the right flags and check the error), or copy the data and work on the copy, or hold a lock that genuinely covers the whole check-and-act — which is only possible if you own all the state.

The same shape appears in Lecture 17’s shell: check the job list, then update it, with a SIGCHLD arriving in between. There the fix was to block the signal across the whole check-and-act, making the pair atomic with respect to the handler.

The general lesson: a lock makes operations atomic; it does not make your assumptions true. Ask what invariant must hold across the whole sequence, then make the sequence atomic — or eliminate the assumption by restructuring (lock-and-copy is the usual tool).


5. Deadlock

5.1 What it looks like

Two threads, two mutexes, opposite orders. Thread A takes (m1, m2); thread B takes (m2, m1). Eventually A holds m1 and wants m2 while B holds m2 and wants m1. Neither releases. 03_deadlock.c:

== 1. opposite lock orders: thread A takes (m1,m2), B takes (m2,m1) ==
  after 800 ms the child is STILL RUNNING and has made no
  progress: A holds m1 and wants m2, B holds m2 and wants m1.
  DEADLOCK confirmed -- killing it with SIGKILL.

How a demo shows a hang and still finishes: the broken version runs in a child process (Lecture 16). The parent polls with waitpid(…, WNOHANG) for 800 ms, concludes deadlock if the child still lives, and kills it with SIGKILL — the one signal that cannot be caught or ignored (Lecture 17), and therefore the only thing that reliably stops a deadlocked process.

The crucial observation: neither thread is wrong by itself. Each locks both mutexes and unlocks both. The bug lives in the relationship between two functions that may have been written by different people, months apart.

5.2 The four necessary conditions

Deadlock requires all four at once:

  1. Mutual exclusion — the resources cannot be shared.
  2. Hold and wait — a thread holding one resource waits for another.
  3. No pre-emption — nobody can forcibly take a lock away.
  4. Circular wait — a cycle in the “waits for” graph.

Break any one and deadlock becomes impossible. In practice, (1) is the point of a lock and (3) is how mutexes work, so the practical targets are (2) and (4).

5.3 The fix: order your locks

Breaking (4) is the standard answer: define a global order on all locks and have every thread acquire them in that order.

/* The convention: m1 is ALWAYS acquired before m2. */
pthread_mutex_lock(&m1);
pthread_mutex_lock(&m2);
== 2. the fix: EVERY thread acquires m1 before m2 ==
  finished in 7 ms (no deadlock possible)
  shared1 = 600000, shared2 = 600000, expected 600000 -> CORRECT

If every thread takes locks in a fixed order, no cycle can form — the “waits for” graph becomes acyclic by construction. The order can be anything consistent (address order, a documented hierarchy, an index), and documenting it is part of the design. Other options:

  • Break hold-and-wait: acquire every lock you need at once with a “lock both” primitive, or release everything before acquiring more.
  • Add pre-emption: use pthread_mutex_trylock and, on failure, release what you hold and retry. This works but risks livelock (threads endlessly backing off in lockstep), so add randomized backoff.
  • Avoid shared state: then there is nothing to lock. Lecture 22’s private accumulators are deadlock-proof for free — the best fix of all.

5.4 Why deadlocks are dangerous

Deadlock is a latent bug: it needs a particular interleaving, so a program can pass tests for months and then stop dead under production load. No amount of testing demonstrates its absence. This is why the discipline is structural — a documented lock order, enforced by review and by tooling (thread sanitizers can detect lock-order inversions even when no deadlock occurs) — rather than empirical.


Summary

  • Producer/consumer needs more than mutual exclusion: two counting semaphores, items (init 0) and slots (init N), plus a mutex. Each side waits on what it consumes and signals what it produces. Verified: 60 000 items through an 8-slot buffer, checksums matching, occupancy bounded 0–8.
  • P(slots) before P(mutex). Blocking on a second resource while holding a lock deadlocks instantly — the specific case of §5’s general rule.
  • Readers/writers lets readers overlap (measured: up to 8 inside at once vs a mutex’s 1) with writers exclusive (0 torn reads). But it is slower than a mutex for short critical sections (0.79×) and much faster for long ones (6.47×): the rule is reads-dominate and long-enough section. It also risks starvation, and POSIX does not specify the policy.
  • Thread safety has four classes: unprotected sharing (lock it), state across calls (pass the state in — strtok 78.5% wrong vs strtok_r 0%), static return buffer (lock-and-copy or _r), and calling any of those. A lock cannot fix Class 2; the interface must change.
  • Some races no lock can fix — TOCTOU, where the logic assumes nothing changed between a check and a use. Make the sequence atomic, or copy, or restructure.
  • Deadlock needs mutual exclusion + hold-and-wait + no pre-emption + circular wait. Break the cycle with a global lock order. Neither thread is wrong alone; the bug is in their relationship, and it is latent — testing cannot prove its absence.

Common pitfalls

  • Using a mutex where you need to count. “Wait until non-empty” needs a semaphore (or a condition variable), not a lock.
  • Taking the mutex before the counting semaphore. Instant deadlock in a bounded buffer.
  • Forgetting how the pipeline ends. A consumer in P(items) with no more producers waits forever; use sentinels or a shutdown flag.
  • Reaching for an rwlock reflexively. For short critical sections it is slower than a mutex. Measure.
  • Assuming rwlock fairness. Readers or writers may starve depending on an unspecified policy.
  • Calling strtok, rand, localtime, ctime, gethostbyname from threads. Use the _r variants (or getaddrinfo).
  • Trying to fix a Class 2 function with a lock. The state spans calls; the interface must change.
  • Assuming a lock makes your assumptions true. TOCTOU survives perfectly correct locking.
  • Inconsistent lock order between two functions written at different times — the deadlock that passes all tests.
  • trylock-and-retry without backoff, which trades deadlock for livelock.
  • Holding a lock while doing I/O or calling unknown code. It may block, or take another lock, and you have just created a hold-and-wait.

Exercises

  1. Why two semaphores? Could you implement the bounded buffer with one semaphore and one mutex? What breaks?

    AnswerNo. You need to block in **two** different situations — buffer empty (consumer waits) and buffer full (producer waits) — and each needs its own count. One semaphore can track one of them; the other condition would be unguarded, so a producer would overwrite a full buffer or a consumer would read an empty slot. The two counts are duals: `items + slots == N` always.
  2. The reversed Ps. Show the exact deadlock when a producer does P(mutex) then P(slots) on a full buffer.

    AnswerThe producer holds `mutex` and blocks in `P(slots)` because the buffer is full. A consumer could free a slot, but to remove an item it must first acquire `mutex` — held by the blocked producer. The consumer blocks in `P(mutex)`. Now the producer waits for a slot only the consumer can create, and the consumer waits for a mutex only the producer can release: a two-thread circular wait.
  3. rwlock or mutex? A cache is read 10 000 times per second and written 10 times; each read is a single pointer dereference. Which lock, and why might the “obvious” answer be wrong?

    AnswerProbably a **mutex** — or an atomic/lock-free read. Reads dominate overwhelmingly, which suggests an rwlock, but the critical section is a *single dereference*, far too short to amortize the rwlock's reader-count bookkeeping; measured here, a short section made the rwlock **slower** than a mutex. The rwlock wins only when readers stay inside long enough to overlap usefully.
  4. Starvation vs deadlock. Distinguish them, and say which the readers/writers problem risks.

    AnswerIn **deadlock** no thread makes progress — a circular wait. In **starvation** the system progresses but one thread is perpetually passed over. Readers/writers risks **starvation**: a reader-preferring lock can starve a waiting writer under a steady stream of readers (and a writer-preferring one starves readers). No cycle exists, so it is not deadlock.
  5. Class and fix. localtime() returns a pointer to a static struct tm. Which class, and give two fixes.

    Answer**Class 3** — it returns a pointer to a static buffer, so a second thread's call overwrites the first's result. Fixes: (a) use **`localtime_r`**, which writes into a caller-supplied `struct tm`; (b) **lock-and-copy** — hold a mutex, call `localtime`, copy the struct into local storage, release the lock, then use the copy.
  6. TOCTOU. Why does adding a mutex around both the access check and the open not fix the race?

    AnswerBecause the shared state is the **file system**, which is outside your mutex entirely. Your lock only excludes your own threads; another *process* (or a symlink swap) can replace the file in the window. The fix must be structural: perform a single operation that checks and acts atomically (`open` with appropriate flags and handle the error), rather than checking and then acting.
  7. Order them. Three locks A, B, C are taken by various functions. Give the rule that makes deadlock impossible, and explain why it works.

    AnswerDefine a total order (say A < B < C) and require every thread to acquire locks in increasing order, releasing in reverse. Then a thread holding a lock only ever waits for a *higher* one, so the "waits for" graph can have no cycle (a cycle would need some thread waiting for a lower lock). With no circular wait, one of the four necessary conditions fails and deadlock cannot occur.

Lab 7 (proxylab) is due around this lecture, and its cache is a textbook readers/writers problem — many concurrent readers, occasional writers, with the starvation and lock-ordering hazards above. Per the course’s academic-integrity policy these notes contain no lab solutions: the demos here use a bounded buffer, a toy array and two bare mutexes, with no cache, no HTTP and no proxy.

Further reading

  • CS:APP3e §12.5.4–§12.5.5 (producer/consumer, readers/writers) and §12.7–§12.8 (thread safety, reentrancy, races, deadlock); practice problems 12.13–12.20.
  • man 3 pthread_rwlock_rdlock, man 3 strtok_r, man 3 pthread_mutex_trylock.
  • For condition variables — the other standard way to express “wait until a predicate holds”, often cleaner than semaphores — man 3 pthread_cond_wait and CS:APP’s discussion of the alternatives.
  • Thread sanitizer (-fsanitize=thread) detects data races and lock-order inversions, including ones that did not deadlock on that run. It is the right tool for exactly the latent bugs this lecture describes.

Preview of Lecture 24: Thread-level parallelism

So far concurrency has been about correctness. Lecture 24 asks what it buys in speed, and the answers are frequently negative. It measures real speedup against thread count on this 12-core machine (8 performance + 4 efficiency cores, which complicates the story), derives Amdahl’s law, and then examines the memory system’s two parting gifts: cache coherence, which makes false sharing turn independent per-thread counters into a contention disaster, and memory consistency, where two threads really can both read 0 from variables the other just set.


术语表 (Glossary, English → 中文)

English中文
producer/consumer problem生产者/消费者问题
bounded buffer有界缓冲区
counting semaphore计数信号量
binary semaphore / mutex二元信号量 / 互斥锁
slots / items空槽 / 产品计数
circular buffer循环缓冲区
occupancy占用量
sentinel (“poison pill”)哨兵值(终止标记)
work queue / thread pool工作队列 / 线程池
readers/writers problem读者/写者问题
shared lock / exclusive lock共享锁 / 排他锁
pthread_rwlock_t读写锁
reader-preferring / writer-preferring偏好读者 / 偏好写者
starvation饥饿
fairness公平性
torn read读到不一致的中间状态
thread safety线程安全
thread-unsafe classes 1-4线程不安全的四类
reentrant function可重入函数
_r variant可重入版本
strtok / strtok_r分词函数
lock-and-copy加锁并复制
static storage静态存储
time-of-check to time-of-use (TOCTOU)检查与使用之间的竞态
deadlock死锁
mutual exclusion互斥
hold and wait持有并等待
no pre-emption不可剥夺
circular wait循环等待
lock ordering锁顺序
trylock尝试加锁
livelock活锁
latent bug潜伏缺陷
condition variable条件变量
thread sanitizer线程检测器
← 返回课程目录