False Sharing and the Cache Line
Cache and NUMA effects are a recurring interview topic at the C++-first firms, and false sharing is the one that most reliably surprises people, because the program has no shared data and behaves as though it does. This lesson walks the coherence protocol through one example slowly enough to see where the cost is, then gives the three fixes with the code for each, and the measurement that proves you found it.
The mechanism
Cache coherence operates on lines, typically 64 bytes (128 on some parts, Apple's M series among them, and Intel's adjacent-line prefetcher pulls in the neighbouring line, so 128 is sometimes the safer padding on x86 too), not on variables. When a core writes to a line, the protocol must invalidate every other core's copy of that line before the write can proceed. Two variables in the same line therefore behave, as far as the hardware is concerned, like one variable.
The rest of this lesson is for subscribers
Unlock every lesson in Systems Programming for Trading, and every other premium course.
Subscribe to continueTest your knowledge
Keep reading Systems Programming for Trading
27 lessons in this course, and every other premium course, on one subscription.
- Every lesson in every course, with the worked examples and interactive simulators
- Graded questions on every lesson, with explanations for the wrong answers as well as the right one
- The trainers, timed assessments and brainteaser library that go with them