Master the fundamental concepts of threads & concurrency through this focused micro-challenge.
A data race occurs when two threads access the same memory location, at least one write is present, and no synchronization orders them. The C memory model calls this undefined behavior; observed output can change run to run.
Compile with -fsanitize=thread:
For example, counter++ without atomics from two threads may report a race at the increment line even if you usually see 1000 as the final value.
ThreadSanitizer, the tool this task exercises, was built at Google after data races caused real, hard-to-reproduce production incidents in Chrome's multi-process renderer and is now standard in Go's -race flag and Rust's Miri. The double-checked-locking bug shown here is a famous real pattern (formalized as broken by the 'C++ and the Perils of Double-Checked Locking' paper) that misled a generation of C++ programmers into shipping racy singleton initialization.
Before you call the implementation done, walk failure modes on purpose. Test empty structures, single-element edge cases, maximum concurrency, and errno paths that must not crash the program. OS code usually fails in production when happy-path tests pass but invariants break under contention or memory pressure.
Keep structures small and name fields after kernel counterparts when possible. That lets you read man pages and kernel source side by side while you work. Print observable events during development; remove noisy logs once tests pass reliably.
You will write a deliberately racy program, run it under TSan, and apply fixes with mutexes or atomics. This exercise requires pasting the TSan report and explaining which invariant the fix restores.
Create race condition and detect with ThreadSanitizer.
Requirements:
Success Criteria:
Three hints are available for this task, revealed one at a time inside the code workspace so you can struggle productively before seeing them.
All starter code and reference implementations are available for your local setup.
View on Github