Maps to: CMU 15-213/15-513/14-513 Fall 2026, Lecture 22 (Nov 19), slide deck
sync-basic. Reading: CS:APP3e §12.4, §12.5.1–§12.5.3. 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/lecture22/. Reading time: ~85 minutes; ~20 more for the demos.
0. How to read this lecture
0.1 Learning goals
After this lecture you should be able to:
- Explain why
cnt++from two threads loses updates, at the level of the generated instructions. - Identify which variables are shared in a threaded program, using the “is it reachable by more than one thread?” test.
- Read a progress graph and say which trajectories are unsafe.
- Define a critical section and mutual exclusion, and enforce them with a mutex, a binary semaphore (
P/V), or an atomic operation. - Compare the costs of those primitives, uncontended and contended, and explain why contention inverts the usual intuition about adding cores.
- Apply the most important optimization: do not share the hot variable — accumulate privately and combine once.
0.2 Prerequisites and scope
- Lecture 21: threads, and what they share (globals, heap, descriptors) versus what is private (stack, registers).
- Lectures 3–5: reading assembly. Demo 03 is a direct application — the race is visible in the instructions.
- Lecture 15: the optimizer. It turns out to matter enormously here (§1.3).
- In scope: CS:APP §12.4–§12.5.3 — shared variables, the
badcntrace, progress graphs, mutual exclusion, mutexes, semaphores, and the cost of each. - Out of scope: producer/consumer, readers/writers, deadlock and thread safety (Lecture 23); parallel speedup and false sharing (Lecture 24).
0.3 Section → code map
| Section | Idea | Demo in code/lecture22/ |
|---|---|---|
| §1 | the race, measured | 01_badcnt.c (at -O0) |
| §1.3 | why the optimizer can hide it | 01_badcnt.c (at -O2) |
| §1.4 | the race in the instructions | 03_why_it_races.py |
| §3–§4 | mutex, semaphore, atomic | 01_badcnt.c |
| §5 | what each costs | 02_sync_cost.c |
1. The simplest broken program
1.1 What should happen, and what does
Four threads, each incrementing one shared long 500 000 times. The answer must be 2 000 000. 01_badcnt.c, compiled at -O0:
cnt++ (unprotected) result 944616 / 2000000 WRONG (1055384 updates lost, 52.77%)
More than half the updates vanished. Not a few, not an edge case — over a million increments had no effect. And nothing in the source hints at it:
for (long i = 0; i < NITERS; i++)
cnt_bad++; /* cnt_bad is a global: shared */
Run it again and you get a different number. That is the signature of a race: the result depends on the order in which unsynchronized operations happen to interleave, and the order is chosen by the scheduler, not by you.
1.2 Which variables are shared?
A variable is shared if more than one thread can reach it. Lecture 21’s table gives the rule:
| Kind of variable | Shared? |
|---|---|
| Global | Yes — one instance, every thread sees it |
static local | Yes — one instance, despite looking local |
| Ordinary local | No — one instance per thread, on its own stack |
| Heap block | Yes, if its pointer is reachable by another thread |
So cnt_bad is shared because it is global — no pointer was passed anywhere. This is why Lecture 21 insisted that sharing is the thing you must argue for: with threads it is the default.
1.3 Why your optimizer may hide the bug
Here is a result worth dwelling on. The same source, compiled at -O2:
cnt++ (unprotected) result 2000000 / 2000000 CORRECT [0 ms]
The race apparently disappeared. It did not. The compiler proved the loop merely adds NITERS to cnt and collapsed a million read-modify-writes into one (Lecture 15’s code motion, applied to a loop whose only effect is an accumulation). With a single operation per thread the window to interleave is tiny, so four threads usually produce the right answer.
This is luck, not safety:
- the variable is still shared;
- that one remaining increment is still not atomic (§1.4);
- the behaviour depends on the optimizer, so it can change with a compiler flag, a compiler version, or an unrelated edit;
- with slightly different code the same optimizer will not collapse the loop and the bug returns.
The practical lesson is uncomfortable and important: a concurrency bug can be invisible at one optimization level and fatal at another. “It passed at -O2” tells you nothing. (This also explains why the textbook’s badcnt is compiled without optimization — and why this lecture’s demo is built both ways.)
1.4 The race, in the instructions
Why is one ++ interruptible? 03_why_it_races.py compiles it and shows you. At -O0, on both architectures, it is exactly what the textbook promises — three memory operations:
arm64 -O0, increment(): x86-64 -O0, increment():
ldr x8, [x9] ; LOAD movq (%rax), %rcx ; LOAD
add x8, x8, #1 ; ADD addq $1, %rcx ; ADD
str x8, [x9] ; STORE movq %rcx, (%rax) ; STORE
A thread can be descheduled between any two of them. If two threads both LOAD the value 100, both ADD to get 101, and both STORE 101, then two increments produced one increase. That is the million lost updates.
At -O2 the two architectures diverge, and the x86-64 result is the subtle one:
x86-64 -O2: incq (%rax) <- ONE instruction
arm64 -O2: ldr / add / str <- still three
Be careful here: one instruction does not mean atomic. incq (%rax) is a single instruction, but the processor still reads, modifies and writes internally, and another core can interleave with that sequence. The whole reason the lock prefix exists is the difference between the two, and it is visible in the atomic version:
x86-64: lock incq (%rax) arm64: ldadd-family atomic add
Those are atomic — indivisible with respect to other cores, with no window to interleave into.
2. Critical sections, mutual exclusion, and progress graphs
The fix is not to make the instructions faster but to forbid the bad interleavings. The region of code that must not be interleaved is a critical section; the property we need is mutual exclusion: at most one thread may be executing it at a time.
A progress graph makes the unsafe region visible. Plot thread 1’s progress on the x-axis and thread 2’s on the y-axis; a point is a state, and execution is a trajectory moving right or up (one step per instruction). Both threads’ critical sections carve out a rectangle — the unsafe region:
thread 2
^
S |. . . . . . . . L,U,S = Load, Update, Store of thread 2
U |. . ┌───────┐ . the box = both threads inside their
L |. . │ UNSAFE│ . critical sections at once
|. . └───────┘ .
+----L---U---S---> thread 1
- A trajectory that enters the box has both threads mid-update, so one update is lost.
- A trajectory that goes around it is safe.
- Mutual exclusion is exactly the guarantee that no trajectory enters the box.
Two things fall out of this picture. First, the unsafe region is a property of the code, not of the schedule — so “it worked when I ran it” only means your trajectory happened to miss the box. Second, the box is as large as the critical section, so short critical sections are safer and faster (fewer trajectories hit them, and less waiting).
3. Mutexes
A mutex (mutual-exclusion lock) is the direct implementation: lock it to enter, unlock to leave, and the implementation guarantees at most one holder.
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_lock(&mutex);
cnt_mutex++; /* the critical section */
pthread_mutex_unlock(&mutex);
pthread_mutex result 2000000 / 2000000 CORRECT
Exactly right, every run. Note what the mutex does not do: it does not make cnt++ indivisible. The three instructions are as interruptible as ever — the mutex guarantees that no other thread is executing that region while you are, which is enough.
Rules that are not optional: lock and unlock in the same function wherever possible (so every path unlocks — an early return inside a critical section is a classic leak), keep the section short, and never lock a mutex you already hold unless it is recursive.
4. Semaphores
A semaphore is a non-negative integer with two atomic operations, named by Dijkstra:
P(s)(proberen, “wait”): wait untils > 0, then decrement it.V(s)(verhogen, “post”): increments, waking one waiter if any.
Initialized to 1 it is a binary semaphore — a lock, used exactly like a mutex:
psem_P(&sem);
cnt_sem++; /* the critical section */
psem_V(&sem);
binary semaphore P/V result 2000000 / 2000000 CORRECT
Initialized to N it becomes a counting semaphore that tracks N available units of a resource — which is what makes semaphores more general than mutexes, and is the whole basis of Lecture 23’s bounded buffer. Note also that a semaphore has no notion of an owner: any thread may V a semaphore it never P’d, which is what lets one thread signal another (a mutex cannot do that).
Portability wart, and why this lecture has a
psemwrapper. CS:APP usessem_init— an unnamed POSIX semaphore. On macOSsem_initis a deprecated stub that fails at run time withENOSYS, “Function not implemented”. Only named semaphores (sem_open) work.psem.ctherefore provides one API over both: on macOS it callssem_openwith a generated unique name and thensem_unlinks it immediately, which removes the name system-wide while leaving the open handle fully usable — so it behaves like an unnamed semaphore and leaves nothing behind on a crash. The mechanism being taught is identical; only the setup differs. This has a large effect on §5’s measurements.
4.1 Atomics: the third option
A third approach skips locking entirely and uses hardware that performs read-modify-write indivisibly:
atomic_long cnt_atomic;
atomic_fetch_add(&cnt_atomic, 1); /* x86: lock incq; arm64: ldadd */
atomic_fetch_add result 2000000 / 2000000 CORRECT
Atomics are ideal for exactly this shape — a single counter or flag. They do not generalize to a multi-step invariant (“remove from list A and add to list B”), which still needs a lock. C11’s <stdatomic.h> makes them portable, and atomic_is_lock_free tells you whether a type is handled by hardware or by a hidden lock.
5. What synchronization costs
Correct is not the end of the story. 02_sync_cost.c times one million increments five ways, at 1 thread and at 4, in nanoseconds per operation:
| scheme | 1 thread | 4 threads | correct? |
|---|---|---|---|
| unsynchronized | 2.36 | 0.93 | NO |
| atomic | 2.39 | 12.03 | yes |
| mutex | 4.21 | 10.22 | yes |
semaphore P/V | 344.67 | 1728.65 | yes (see caveat) |
| private + combine | 0.29 | 0.11 | yes |
Four things to read off it.
Uncontended, an atomic costs about the same as no synchronization at all (2.39 vs 2.36 ns/op). Both are a single read-modify-write, and with nobody to interfere the atomic’s guarantee is nearly free. A mutex adds a little (4.21) for its lock/unlock bookkeeping.
Contention inverts everything. Going from 1 thread to 4, the shared schemes get slower per operation — atomic 2.39 → 12.03, mutex 4.21 → 10.22. Four cores doing the work produced fewer operations per second than one. The reason is not the lock’s logic but the memory system: all four cores are competing for the one cache line holding cnt, which must bounce between their caches. Lecture 24 measures this effect head-on.
The best synchronization is none. private + combine — each thread accumulates in its own local and the totals are summed once at the end — is an order of magnitude cheaper than anything else, and it is the only correct scheme that gets faster with more threads (0.29 → 0.11 ns/op), because there is nothing to contend for. Demo 03 shows why it needs no lock: the accumulator never touches shared memory.
So the engineering ranking is not “which lock is fastest” but:
- restructure so threads do not share the hot data (private + combine);
- if they must share a single value, use an atomic;
- if the invariant spans several operations, use a mutex, and keep the critical section short;
- use a semaphore when you need counting or signalling, not plain mutual exclusion.
Caveat on the semaphore row. Those numbers are a macOS artefact, not a property of semaphores. Because
sem_initdoes not work there,psemuses named semaphores, which are kernel objects — so everyPandVis a system call, whilepthread_mutexhas a user-space fast path and needs no syscall when uncontended. Hence the ~80× gap. On Linux,sem_waiton an unnamed semaphore is a futex with a user-space fast path and would land near the mutex. Compare mutex against atomic for a fair reading, and do not conclude “semaphores are slow”.
Summary
cnt++on a shared variable is a race: measured, 4 threads lost 1 055 384 of 2 000 000 updates (52.8%) at-O0, with a different number every run.- A variable is shared if more than one thread can reach it: globals and
staticlocals always, heap blocks if the pointer escapes, ordinary locals never. - The optimizer can hide the bug. At
-O2the same program printed the correct answer, because the loop was collapsed into one add. That is luck: the variable is still shared and the operation still not atomic. A concurrency bug invisible at one optimization level can be fatal at another. - At
-O0,cnt++is LOAD, ADD, STORE on both architectures — a thread can be descheduled between any two. At-O2, x86-64 emits a singleincqwhich is still not atomic: one instruction ≠ atomic, which is exactly what thelockprefix is for. - A critical section needs mutual exclusion; a progress graph shows the unsafe region as a box no trajectory may enter. Shorter critical sections mean a smaller box.
- Three fixes, all exactly correct: a mutex (excludes other threads from the region), a binary semaphore (
P/V, and generalizes to counting and signalling), an atomic (makes the operation indivisible). - Costs, measured: uncontended, atomic ≈ unsynchronized (2.4 ns/op) < mutex (4.2). Contended, the shared schemes get slower with more cores (atomic 12.0, mutex 10.2).
private + combine(0.29 → 0.11) is the only correct scheme that scales.
Common pitfalls
- Assuming
x++is atomic. It is one character and up to three memory operations. - Concluding “no bug” from a passing run — or from a passing optimization level. Races are reasoning errors, not testing problems.
- Forgetting that globals and
staticlocals are shared even when no pointer is passed. - An early
returninside a critical section, skipping the unlock. Every path must unlock. - Over-long critical sections. A big unsafe box costs both safety margin and throughput.
- Using
volatileas synchronization. It prevents caching the value in a register; it does not make read-modify-write atomic and it does not order other accesses. - Assuming more cores means more throughput on a shared counter. Measured here: it means less.
- Using
sem_initin portable code — it is a non-functional stub on macOS. - Ignoring
EINTRfromsem_wait. A signal can make it fail without acquiring; retry, or you proceed without the semaphore. - Reaching for a lock before asking whether the data must be shared at all.
Exercises
-
How can two increments make one? Walk through the instruction interleaving that loses an update, with both threads starting from
cnt == 100.Answer
T1 LOADs 100. T2 LOADs 100 (before T1 stores). T1 ADDs → 101, STOREs 101. T2 ADDs its own copy → 101, STOREs 101. Two increments ran; `cnt` went from 100 to 101. The lost update is T1's, overwritten by T2's stale-based store. -
Shared or not? Classify: a global
int total; astatic int callsinside a function; a localchar buf[64]; amalloc’d array whose pointer is stored in a global.Answer
Shared: the global `total`; the `static` local `calls` (one instance for the whole program despite its scope); and the heap array (the heap is shared and the pointer is reachable). Not shared: `buf`, which lives on the calling thread's own stack — one instance per thread. -
The
-O2trap. Your racy program gives the right answer at-O2and the wrong one at-O0. Is it correct? What do you tell a colleague who wants to ship it?Answer
It is **not** correct. At `-O2` the optimizer collapsed the loop into a single read-modify-write, shrinking the race window — the variable is still shared and that operation is still not atomic. The behaviour depends on the optimizer, so a compiler upgrade or an unrelated edit can restore the bug. Fix the race (atomic, mutex, or private accumulation); do not ship a program whose correctness rests on a code transformation you did not ask for. -
One instruction, still broken. On x86-64 at
-O2,cnt++becomes a singleincq (%rax). Why is that not enough, and what makeslock incqdifferent?Answer
A single instruction is not a single *indivisible memory transaction*: the CPU internally loads, modifies and stores, and another core can read or write that location in between. The `lock` prefix makes the whole read-modify-write atomic with respect to other processors (by holding the cache line exclusively for its duration), which is precisely the guarantee `incq` alone lacks. -
Progress graph. Both threads’ critical sections form a box in the progress graph. What does a trajectory passing through the box mean, and what does mutual exclusion correspond to geometrically?
Answer
A trajectory inside the box is a state where **both** threads are executing their critical sections simultaneously — the interleaving that loses the update. Mutual exclusion is the guarantee that **no trajectory ever enters the box**; legal executions must route around it, which is what a lock forces by making one thread wait at the boundary. -
Mutex or atomic? You need (a) a hit counter incremented by many threads, and (b) moving an element from list A to list B. Which primitive for each, and why?
Answer
(a) An **atomic** increment: one location, one read-modify-write, no lock needed, and cheapest when uncontended. (b) A **mutex**: the invariant spans several operations (remove from A *and* insert into B) and must be indivisible as a whole; no single atomic can express it. Atomics protect one location, locks protect an *invariant*. -
Why did 4 threads get slower? The atomic went from 2.39 ns/op at 1 thread to 12.03 at 4. Explain, and give a restructuring that avoids it.
Answer
All four cores contend for the single cache line holding the counter. To perform an atomic read-modify-write a core must hold that line **exclusively**, so the line ping-pongs between caches and each operation pays a coherence miss instead of a cache hit. The fix is to stop sharing the hot location: give each thread its own counter and sum them once at the end (`private + combine`, measured at 0.11 ns/op with 4 threads) — and pad those counters to separate cache lines, which is Lecture 24's false sharing.
The related lab
Lab 8 (sfslab) is assigned around this lecture, and the proxy lab’s cache needs exactly this material. Per the course’s academic-integrity policy these notes contain no lab solutions: the demos synchronize a single counter, with no file system, no cache and no proxy.
Further reading
- CS:APP3e §12.4–§12.5.3 (shared variables,
badcnt, progress graphs, semaphores) and practice problems 12.7–12.12. §12.5’sgoodcntis demo 01’s mutex/semaphore version. man 3 pthread_mutex_lock,man 3 sem_open,man 3 sem_wait; and<stdatomic.h>in the C11 standard for the atomics.- Dijkstra’s original “Cooperating Sequential Processes” (1965) for
P/Vin the author’s own words — still remarkably readable. - Herb Sutter, “The Free Lunch Is Over” (2005), for why this lecture became mandatory.
Preview of Lecture 23: Synchronization — advanced
Mutual exclusion is only the first problem. Lecture 23 covers the ones it cannot solve: the producer/consumer problem, where two counting semaphores bound a shared buffer and a mutex protects it; the readers/writers problem and its starvation hazard; thread safety as a set of classes (and why strtok is unsafe while strtok_r is fine); races that locks cannot fix at all (time-of-check/time-of-use); and deadlock, demonstrated with inconsistent lock ordering and fixed by ordering the locks.
术语表 (Glossary, English → 中文)
| English | 中文 |
|---|---|
| synchronization | 同步 |
| shared variable | 共享变量 |
| race (condition) | 竞态条件 |
| lost update | 更新丢失 |
| interleaving | 交错执行 |
| schedule / trajectory | 调度 / 轨迹 |
| progress graph | 进度图 |
| unsafe region | 不安全区域 |
| critical section | 临界区 |
| mutual exclusion | 互斥 |
| mutex | 互斥锁 |
pthread_mutex_lock / unlock | 加锁 / 解锁 |
| lock contention | 锁竞争 |
| semaphore | 信号量 |
| binary semaphore | 二元信号量 |
| counting semaphore | 计数信号量 |
P operation (wait) | P 操作(等待) |
V operation (post) | V 操作(释放) |
sem_init / sem_open | 初始化 / 打开信号量 |
| named / unnamed semaphore | 有名 / 无名信号量 |
| atomic operation | 原子操作 |
| read-modify-write | 读-改-写 |
lock prefix (x86) | lock 前缀 |
atomic_fetch_add | 原子加 |
| lock-free | 无锁 |
volatile | 易变(不等于同步) |
| cache line contention | 缓存行竞争 |
| private accumulator | 私有累加器 |
| system call overhead | 系统调用开销 |
| futex / user-space fast path | futex / 用户态快速路径 |