Project 4: False Sharing Detector
A multithreaded program that demonstrates the performance penalty of false sharing. It will have two modes: a “bad” mode where two threads hammer adjacent integer counters, and a “good” mode where the counters are padded to lie on separate cache lines.
Quick Reference
| Attribute | Value |
|---|---|
| Primary Language | C |
| Alternative Languages | C++, Rust |
| Difficulty | Level 3: Advanced |
| Time Estimate | 1-2 weeks |
| Knowledge Area | Concurrency / CPU Caches / Multithreading |
| Tooling | pthreads (or std::thread in C++), GCC/Clang |
| Prerequisites | Basic multithreading concepts (creating threads, joining them). |
What You Will Build
A multithreaded program that demonstrates the performance penalty of false sharing. It will have two modes: a “bad” mode where two threads hammer adjacent integer counters, and a “good” mode where the counters are padded to lie on separate cache lines.
Why It Matters
This project builds core skills that appear repeatedly in real-world systems and tooling.
Core Challenges
- Creating and managing threads → maps to pthreads or other threading libraries
- Designing a data structure to induce false sharing → maps to placing variables next to each other
- Designing a data structure to prevent false sharing → maps to using padding to separate variables
- Accurately benchmarking the threaded code → maps to joining threads and using a high-res timer
Key Concepts
- False Sharing: Scott Meyers’ “Cpu Caches and Why You Care” talk (YouTube)
- Cache Coherency Protocols (MESI): Wikipedia provides a good overview.
- Padding and Alignment: “Effective C” Ch. 2 - Robert C. Seacord
Real-World Outcome
$ ./false_sharing_detector
Running with false sharing (adjacent counters):
Thread 0 and 1 finished in 4.51 seconds.
Running with padding (counters on separate cache lines):
Thread 0 and 1 finished in 0.35 seconds.
Performance Ratio (bad/good): 12.88x
Implementation Guide
- Reproduce the simplest happy-path scenario.
- Build the smallest working version of the core feature.
- Add input validation and error handling.
- Add instrumentation/logging to confirm behavior.
- Refactor into clean modules with tests.
Milestones
- Milestone 1: Minimal working program that runs end-to-end.
- Milestone 2: Correct outputs for typical inputs.
- Milestone 3: Robust handling of edge cases.
- Milestone 4: Clean structure and documented usage.
Validation Checklist
- Output matches the real-world outcome example
- Handles invalid inputs safely
- Provides clear errors and exit codes
- Repeatable results across runs
References
- Main guide:
LEARN_C_PERFORMANCE_DEEP_DIVE.md - “C++ Concurrency in Action” by Anthony Williams (concepts are transferable)