Go deeper — read the bookCache lines & false sharing— runnable code & full walkthrough →

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 line
struct Padded {
alignas(64) std::atomic<long> a;
alignas(64) std::atomic<long> b;
};

What this lesson walks through

  1. 01Two threads, two separate counters
  2. 02a and b share ONE 64-byte cache line
  3. 03Core 0 writes a -> Core 1 invalidated
  4. 04Core 1 writes b -> Core 0 invalidated
  5. 05Ping-pong = FALSE sharing
  6. 06Fix: alignas(64) -> separate lines
  7. 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.

← Previous
Concurrency: Lock-Free Queue — Michael-Scott CAS Loop, ABA, Memory Hazards
Next →
std::future, promise & async