Skip to content
BIASED

Synchronization

Lost updates, critical sections, RISC-V/C11 atomics, mutexes, condition variables, semaphores, deadlock and memory ordering.

The lost update

Two threads each run counter++ a million times — expect 2,000,000; at -O0 you get ~1e6. On RISC-V that is lw / addi / sw. Of 20 interleavings 18 lose an update: both loaded the same value.

Dijkstra’s semaphore is an integer with two atomic operations (Dijkstra, 1965): P, or sem_wait, waits until the value is positive and then decrements it; V, or sem_post, increments it and wakes a waiter if there is one. A semaphore initialized to 1 is a lock: sem_wait enters, sem_post leaves. A semaphore initialized to nnn admits up to nnn threads at once, for example to limit the number of open connections. A semaphore initialized to 0 is a signal: one thread waits on it until another posts.

A critical section is a piece of code that accesses shared data and must not run in two threads at once; here, the three instructions of counter++. A solution to the critical-section problem must guarantee mutual exclusion (at most one thread inside at a time), progress (if the section is free and some threads want to enter, one of them gets in) and bounded waiting (a thread that asked to enter is not overtaken forever) (Arpaci-Dusseau, 2018, chapter 28).

Critical sections and atomics

A critical section needs mutual exclusion. Atomic RMW: LR/SC on RISC-V or C11 atomic_fetch_add. Plain ++ is not atomic.

The previous note gave a program several threads over one address space, and its example was correct only because the threads ran one after the other. Threads exist to run at the same time, on different cores or interleaved on one, and then the scheduler, the caches and the compiler decide the order of their memory accesses. This note shows how an update as simple as counter++ goes wrong when two threads do it at once, explains the failure at the level of the instructions, and builds the tools that prevent it: atomic instructions, locks, condition variables and semaphores. It ends with deadlock, the failure that locks bring with them, and with a short look at memory ordering.

Key idea. A sequence of instructions is atomic only if something makes it so. Either the hardware performs the whole read-modify-write as one indivisible instruction, so no other core can access the word in between, or a lock, itself built on such an instruction, lets one thread at a time run the whole sequence.

Mutex, CV, semaphore

A mutex — one thread in the CS. CV: wait for a predicate in a while under the mutex; cond_wait drops the lock while sleeping. A semaphore is a wait/post counter.

This is a race condition: the result depends on the timing of the threads. Of the 20 possible interleavings of one increment by each thread (choose which 3 of the 6 steps belong to A), only the 2 that run one thread’s three steps entirely before the other’s give 7; the other 18 lose an update (the Code section enumerates them). On two cores the threads really run in parallel, each iteration takes a few nanoseconds, and the windows overlap constantly; that is why so many of the two million increments were lost.

C11 atomics give portable access to these instructions through <stdatomic.h> (ISO/IEC 9899:2018, §7.17). A variable declared atomic_long counter is updated with atomic_fetch_add(&counter, 1); atomic_compare_exchange_strong(&x, &expected, desired) stores desired only if x still equals expected. With the default, sequentially consistent ordering, the RISC-V specification maps an atomic read-modify-write such as atomic_fetch_add to an AMO with both bits set, amoadd.w.aqrl (RISC-V Unprivileged ISA, “Code porting and mapping guidelines”). In the Code section the atomic counter reaches exactly 2,000,000 on every run.

Deadlock and memory ordering

Deadlock needs the four Coffman conditions (mutual exclusion, hold-and-wait, no preemption, circular wait); the practical cure is one global lock-acquisition order. The memory model decides which reorderings are visible: bare stores can leave another core seeing stale values until a fence or a release/acquire atomic. Start with sequentially consistent atomics; weaken only with a proven design.

LR/SC failure modes: an intervening store from another hart to the reservation set clears the reservation and sc returns nonzero — the loop retries. Spurious failures happen; the loop must stay correct under retry. CAS on other ISAs is the same pattern in one instruction. Prefer clear mutex critical sections before inventing lock-free structures; with CVs always re-check the predicate after wake-up. ThreadSanitizer catches many races that review misses.

A correct-looking result proves nothing. Compiled with -O2, the same racy counter program can print 2,000,000 because the optimizer turned each thread’s loop into one addition of 1,000,000 — the race window shrinks but does not vanish.

A mutex that is already locked parks the waiter on a queue; spinning forever wastes energy unless the critical section is a handful of cycles on a dedicated core. Hybrid locks spin briefly then sleep. Priority inversion — a low-priority holder blocking a high-priority waiter — is why real-time systems add priority inheritance. Counting semaphores for a pool of NN identical resources initialize to NN; each wait takes one, each post returns one.

Next: Inter-process communication — cooperating without a shared heap.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Go deeper — optional

Code and labs do not count toward the main percentage or the certificate.

  • Lost update and a critical sectionoptional

    Two threads +=1 without/with mutex: show the counter race and fix it with a critical section.

    ~20 min · easier on a computer · The matching course topic has been read.

    Self-check in the notebook — not part of mastery or the certificate.

Full notes

Answers are saved on the server and tied to this browser until you sign in.