Sub topic 16
False sharing between threads
This chapter assumes you know what a cache line is, how threads and atomics work in C++, and that cores keep private caches. Cache lines are usually 64 bytes, though that size is common rather than guaranteed.
What false sharing is
Cores keep their caches coherent one line at a time, not one variable at a time. When a core writes to a line, every other core's copy of that line becomes invalid. The next core that touches the line must fetch it again.
False sharing happens when two threads write to different variables that sit in the same cache line. The threads share no data, yet the hardware treats them as if they did. The line bounces between cores, and each bounce costs far more than a normal cache hit.
A reproducible example
Two counters declared next to each other will probably share a line. Each thread increments only its own counter.
#include <atomic>
#include <cstdint>
#include <thread>
#include <functional>
struct Counter {
std::atomic<std::uint64_t> value{0};
};
struct alignas(64) PaddedCounter {
std::atomic<std::uint64_t> value{0};
};
template <class C>
void hammer(C& a, C& b) {
auto work = [](C& c) {
for (int i = 0; i < 50'000'000; ++i)
c.value.fetch_add(1, std::memory_order_relaxed);
};
std::thread t1(work, std::ref(a));
std::thread t2(work, std::ref(b));
t1.join();
t2.join();
}
int main() {
Counter shared[2]; // both counters likely sit in one cache line
PaddedCounter apart[2]; // each counter gets its own 64-byte line
hammer(shared[0], shared[1]);
hammer(apart[0], apart[1]);
}Counter is 8 bytes, so both elements of shared fit in one 64-byte line. alignas(64) rounds each PaddedCounter up to 64 bytes and aligns it to a line boundary, so apart[0] and apart[1] are on different lines. The work is identical. On a multicore machine, the padded version typically runs several times faster.
Fixing it
- Pad or align per-thread data to the line size, as above.
- Give each thread a local accumulator and combine the results once at the end. This also removes the shared writes entirely.
- Group data by writer. Keep fields that one thread writes together, and separate them from fields other threads write.
C++17 offers std::hardware_destructive_interference_size in <new> as a portable name for the line size. Not every compiler ships it yet, so a hard-coded 64 is a common fallback.
Costs and limits
Padding trades memory for speed. Padding thousands of small objects to 64 bytes wastes cache space and can slow down code that reads them sequentially. Apply it only to data that threads write often.
Read-only sharing is harmless. Many cores can hold the same line unmodified. The problem requires at least one writer.
Exercise
Four threads each increment their own std::uint64_t in a plain array counts[4]. The program is slower with four threads than with one. Why, and what are two ways to fix it?
Show answer
The four 8-byte counters share one 64-byte cache line. Every write invalidates the line in the other cores, so they spend their time reloading it (false sharing). Fixes: align each counter to its own cache line with alignas(64), or have each thread count in a local variable and write the total to the array once at the end.