Unit 4 of 9 · about 3 hours · explain, measure
Data races, lost updates and lost wakeups
Programming's synchronization-hazards unit showed a lost update behind a barrier and a lock-order deadlock in Python. Here the same defects move to C pthreads, where a data race is undefined behavior and only the sanitizer or a controlled schedule counts as evidence. It assumes that unit as background and never reuses its barrier demo.
You'll be able to
- Separate a data race (unsynchronized access, undefined behavior in C) from a race condition (order-dependent wrong result) with an example of each.
- Reproduce a lost update and a lost wakeup on demand, and show the sanitizer report that convicts the first.
- Measure a racy counter across repeated runs and explain why no single run states the rule.
Covers
Read
In this order, only the parts listed
0 of 5 done
- Non-deadlock bugsOperating Systems: Three Easy Pieces - concurrency
Sections 32.1 and 32.2: atomicity violations and order violations with the before and after code
- Race Conditions and Critical SectionsAlgoMaster Concurrency lessons
Common Race Condition Patterns (read-modify-write, check-then-act, combining thread-safe operations); Race Condition vs Data Race
- Lost Signal / WakeupAlgoMaster Concurrency lessons
What is a Lost Signal; Common Scenarios That Cause Lost Signals; How to Prevent Lost Signals
Read the scenarios; the while-loop proof is the locks unit.
- Spurious WakeupAlgoMaster Concurrency lessons
What is a Spurious Wakeup; Why Spurious Wakeups Exist; Correct Handling Patterns
- Spurious wakeups in the cond contractLinux man-pages: pthreads and futex
pthread_cond_waitpage: spurious wakeups and why the predicate must be re-checked
Focus on
- A data race is a property of two accesses; a race condition is a property of an outcome. The synchronized-map get-then-put has no data race and still loses updates.
- gcc 15.2
-O2compiles a plain-global increment loop into oneaddq $2000000per thread, so the classic demo printed the exact total of 4000000 in five of five runs on an i9-12900K with Linux 7.0. The race is still there: TSan reports a read and write on globalcountin the same build. volatilerestores per-iteration accesses, so the demo loses updates again (twelve runs landed between 2.0 and 2.32 million, never 4000000), butvolatileadds no atomicity or ordering. It is a measurement harness, not a fix.- A condition signal with no waiter is lost, and a wait may return spuriously. Both force the same discipline: wait in a while loop over shared state.
Common mistakes · 3
- An exact total is not a proof. Optimization level, core placement and timing move the number; only TSan or a forced schedule settles existence.
- Removing the data race does not remove the race condition. Locking each map access still loses the get-then-put update; the sequence needs one critical section.
- Sleep-timed reproduction is not deterministic. A passing sleep-timed run can miss the schedule; barriers and sleep-string shims force it.
Try it yourself
Closed-book, before checking anything
-O2 -pthread: record five runs printing 4000000, then rebuild with -fsanitize=thread and keep the data-race report naming global count. Then build the volatile variant and record six runs, none reaching 4000000. State CPU, kernel, compiler, flags, repeat counts and warm caches with every number.Quiz yourself
Answer first, then mark it. Missed ones go to Review.
0 got · 0 missed
1.The plain counter prints 4000000 five times and TSan reports a race. Which result is the finding?Answer
The TSan report. The total is one schedule plus one optimization; the race exists on every run regardless of the printed number.
2.Can a TSan-clean program still have a race condition? Give the example.Answer
Yes. Individually locked get and put on a shared map compose a lost update with no unsynchronized access. Zero data races do not imply a correct sequence.
3.Why is
volatilethe wrong fix for the racy counter?AnswerIt restores per-iteration memory traffic so updates interleave visibly, but concurrent read-modify-write stays a data race: still undefined behavior and still lost updates, now merely observable.
4.A signal sent before any waiter is lost. Which two mechanisms prevent the loss?Answer
A predicate re-checked in a while loop, so a thread sleeps only while the state says so; and designs where the state change itself is observable, such as sequence counters or close flags, rather than the bare signal.
Practice
- OSTEP thread API homework:
main-raceunder ThreadSanitizer, plus signal orderingthreads-apifolder: buildmain-race.cwithgcc -g -pthread -fsanitize=threadand keep the race report; then comparemain-signal.cwithmain-signal-cv.cThe
READMEuses valgrind's helgrind; ThreadSanitizer, built into gcc and clang, reports the same race. Answer theREADMEquestions with whichever detector you have.
You're done when
You can produce a wrong total, a TSan report and a lost signal on demand, and explain why each proves something different.
Only when you can do this without notes.
Leads to
Notes
Resources · 3 for this unit, 6 more in the section
- Operating Systems: Three Easy Pieces - concurrencyRemzi and Andrea Arpaci-Dusseau · primary
Read Chapters 26-33 in order: threads, thread API, locks, locked data structures, condition variables, semaphores, bugs and event-based concurrency. Write the safety and liveness invariant before reading each worked pattern.
- AlgoMaster Concurrency lessonsAlgoMaster · support
Use the named lessons only: Processes vs Threads, Race Conditions and Critical Sections, Mutex, Condition Variables, Compare-And-Swap, Atomic Operations, Semaphores, Producer-Consumer Pattern, Bounded Buffer, Design Thread-Safe Blocking Queue, Barriers and Latches, Read-Write Locks, Coarse-grained vs Fine-grained Locking, Deadlock, Livelock, Starvation, Priority Inversion, Lost Signal/Wakeup, Spurious Wakeup, Concurrency Models and Thread Pool Pattern. Each unit names its lessons; read no other chapter for this section.
- Linux man-pages: pthreads and futexLinux man-pages project · reference
Look up the exact pthread mutex, condition variable, barrier, cancellation and timed-wait contracts plus futex(2) and pthreads(7). Read the stated pages; do not browse the whole manual.
Also in this section
- OSTEP concurrency homework and codeOSTEP authors · required
Use x86.py and the main, vector, condition-variable and semaphore exercises to enumerate schedules. Preserve one lost update, one deadlock and one lost wakeup as minimized tests, then repair each invariant.
- AlgoMaster Concurrency - four bounded contractsAlgoMaster · required
Attempt Design a Closable Bounded Queue, Design Thread-Safe Rate Limiter, Design a Deadlock-Free Two-Key Executor, Design an Atomic Maximum With Compare-and-Swap, Design Deferred Callback Executor and Design Task Scheduler with Dependencies. For each, add a changed input, a deterministic failure schedule and an independent stress test outside the platform.
- MIT 6.1810 - locks and parallelismMIT PDOS · depth
Use Lectures 12-14 and one lock-lab exercise only after the user-space bounded queue passes. Measure the contention change and explain the invariant preserved by the revised locking scheme.
- cppreference: C atomic operationscppreference · reference
Read
atomic_compare_exchangefor success and failure semantics and the expected-pointer update rule, andmemory_orderfor the six orderings and what relaxed permits. Stop before lock-free-property macros. - GCC __atomic builtinsGNU Compiler Collection · reference
Read
__atomic_compare_exchange,__atomic_loadand__atomic_storefor the expected-pointer update rule and the__ATOMIC_RELAXEDconstant used by the CAS reproduce step. - The Little Book of SemaphoresGreen Tea Press · support
Use the rendezvous, barrier and reader-writer puzzles as extra semaphore practice after OSTEP Chapter 31. Skip the Python event material; this section works in C with pthreads.