multithreading · medium
False Sharing & Cache Lines
Two threads write separate variables that share a cache line, causing coherence ping-pong - and how alignas(64) fixes it.
🔑 Key line
False sharing: unrelated variables in one cache line make cores invalidate each other; fix with alignas(64) padding.
The code
struct Counters { std::atomic<long> a; // only Thread A writes a std::atomic<long> b; // only Thread B writes b}; // a and b are adjacent -> SAME 64-byte cache line
// Fix: give each its own cache linestruct Padded { alignas(64) std::atomic<long> a; alignas(64) std::atomic<long> b;};What this lesson walks through
- 01Two threads, two separate counters
- 02a and b share ONE 64-byte cache line
- 03Core 0 writes a -> Core 1 invalidated
- 04Core 1 writes b -> Core 0 invalidated
- 05Ping-pong = FALSE sharing
- 06Fix: alignas(64) -> separate lines
- 07No invalidation -> full speed
Thread A only ever writes counter a; Thread B only writes b. They share no variable, so it looks completely independent.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of False Sharing & Cache Lines and 100+ animated C++ interview lessons.