Last updated:2026-10-12
C++ False Sharing and Cache Lines¶
I recently came across a piece of code that performs alignment manually, so I looked into what impact misalignment can have.
template <typename T>
class AtomicWithPadding {
private:
static constexpr int kCacheLineSize = 64;
uint8_t padding_before[kCacheLineSize];
public:
std::atomic<T> value;
private:
uint8_t padding_after[kCacheLineSize];
};
This leads straight into a must-know interview topic:
- Cache line
Here are a few interview questions that follow from it — can you answer them?
- What is a cache line?
- What is the MESI protocol?
- What is false sharing?
- How do you guarantee avoiding false sharing in C++?
- What benefits can avoiding false sharing bring?
- Do you know which two variables C++17 and later provide to solve this problem?
So I found a performance test whose general idea is:
- Define 4 variables a, b, c, d, shared among multiple threads
- In the other case, align these four variables, then spawn n threads to be scheduled.
Here is the benchmark:
------------------------------------------------------------------
Benchmark Time CPU Iterations
------------------------------------------------------------------
singleThread 4.05 ms 4.04 ms 133
directSharing/real_time 8.78 ms 0.069 ms 77
falseSharing/real_time 8.81 ms 0.083 ms 74
noSharing/real_time 1.16 ms 0.071 ms 578
You can see that noSharing achieves an excellent result! The cache hit rate improves greatly; of course, analyzing it with perf would be even better, to look at the L1 cache misses.
The answers above have been published in the Knowledge Planet — feel free to join the discussion or exchange thoughts in the comments, thanks~
Related Topics¶
- C++ Concurrency in Action Reading Guide | C++那些事
- C++ Deadlock Troubleshooting | C++那些事
- C++ SIMD Vectorization | C++那些事
- C++17 Parallel STL | C++那些事
- GDB Multi-Threaded All-Stop Debugging | C++那些事
- Helgrind Concurrency Error Detection | C++那些事
- libev Event Loop Internals | C++那些事
- C++ std::thread Implementation Internals | C++那些事
- C++ std::thread and jthread | C++那些事
- Getting Started with C++ Multithreading | C++那些事