Sub topic 16
False sharing between threads
This chapter explains how two threads can slow each other down without sharing any data. You should already know what a cache line is, how a struct is laid out in memory, and how to start threads and join them in C++. You don't need to know cache coherence protocols in detail. The chapter explains the parts you need.
What false sharing is
Earlier chapters showed that a CPU moves memory in cache lines, usually 64 bytes. A core never loads a single variable. It loads the whole line that contains the variable.
That is fine for one thread. With several threads on different cores, each core keeps its own copy of the line in its private cache. The hardware must keep those copies consistent. This is called cache coherence.
False sharing happens when two threads write to different variables that sit in the same cache line. The program is correct, because the threads never touch the same variable. The hardware cannot see that, because it tracks ownership per line, not per variable. Each write by one core invalidates the other core's copy, and the line moves back and forth between the cores.
How the hardware treats a shared line
Most CPUs use a protocol in the MESI family. A line in a core's cache is in one of these states:
| State | Meaning |
|---|---|
| Modified | This core has the only copy, and it has been changed. |
| Exclusive | This core has the only copy, and it is unchanged. |
| Shared | Several cores may hold unchanged copies. |
| Invalid | This copy is stale and cannot be used. |
A core must hold a line in the Modified or Exclusive state before it can write to it. If another core holds the line, the writer must first make that core invalidate its copy.
Every arrow after the first is a transfer between cores. A transfer costs tens to hundreds of cycles, which is far more than the add instruction that caused it. The loop spends most of its time waiting for the line.
Reproducing it
The code below is the example from the plan, completed with a timer so you can see the difference. Counter has an 8-byte value, so two adjacent counters fit in one 64-byte line. PaddedCounter is aligned to 64 bytes, so each counter gets its own line.
#include <atomic>
#include <chrono>
#include <cstdint>
#include <functional>
#include <iostream>
#include <thread>
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();
}
template <class C>
double time_ms(C& a, C& b) {
auto start = std::chrono::steady_clock::now();
hammer(a, b);
auto stop = std::chrono::steady_clock::now();
return std::chrono::duration<double, std::milli>(stop - start).count();
}
int main() {
Counter shared[2]; // both counters likely sit in one cache line
PaddedCounter apart[2]; // each counter gets its own 64-byte line
std::cout << "same line: " << time_ms(shared[0], shared[1]) << " ms\n";
std::cout << "separate lines: " << time_ms(apart[0], apart[1]) << " ms\n";
}Compile it with g++ -O2 -std=c++17 -pthread false_sharing.cpp. On a typical multicore x86-64 machine, the first line is often several times slower than the second. The exact ratio depends on the CPU, and a single-core machine shows no difference.
Two details of this example matter:
alignas(64)raises the alignment of the struct. The compiler also roundssizeof(PaddedCounter)up to 64, so array elements start on separate lines.memory_order_relaxedkeeps the atomic operation cheap. The slowdown comes from the cache line, not from ordering constraints.
Where false sharing hides
The counters above are an obvious case. Real programs hide it in less obvious places:
- Per-thread statistics in an array. An array like
long hits[NUM_THREADS]puts eight threads' counters in one line. This is the most common case. - A lock next to the data it protects. Threads spinning on the lock keep invalidating the line that holds the data.
- Adjacent heap objects. Two small objects from the allocator can land in the same line, even if different threads own them.
- Work queues. A producer's write index and a consumer's read index in the same struct share a line.
- Output arrays split by thread. If thread
twritesout[i]for everyi % T == t, neighbors constantly write to the same lines. Giving each thread a contiguous range avoids this.
Read-only sharing does not cause the problem. Many cores can hold a line in the Shared state at no cost. Only writes force invalidation, so one writer next to several readers is still a problem.
Fixing it
There are three common fixes, and you should pick by cost.
Pad or align the hot data. Use alignas(64) as above, or insert explicit padding. The cost is memory. A padded counter uses 64 bytes instead of 8.
Keep state thread-local, then combine. Each thread accumulates into a local variable and writes the result once at the end. This removes the contention instead of hiding it, and it is usually the best fix for counters and sums.
#include <cstdint>
#include <iostream>
#include <thread>
#include <vector>
int main() {
const int threads = 4;
std::vector<std::uint64_t> results(threads, 0);
std::vector<std::thread> pool;
for (int t = 0; t < threads; ++t) {
pool.emplace_back([t, &results] {
std::uint64_t local = 0; // lives in a register or on this thread's stack
for (int i = 0; i < 50'000'000; ++i)
++local;
results[t] = local; // one shared write per thread
});
}
for (auto& th : pool) th.join();
std::uint64_t total = 0;
for (auto v : results) total += v;
std::cout << total << "\n";
}The results array still shares lines, but each thread writes to it once, so the cost is negligible.
Partition the data by line. Assign each thread a contiguous block of an array, aligned to line boundaries where practical, so threads write to different lines.
Trade-offs and limits
Padding costs cache space. If you pad every small object to 64 bytes, you lose the density you gained from the earlier chapters on struct layout. Pad only data that is written often by different threads. Data that is read mostly, or written by one thread, should stay compact.
Placing hot data from different threads in separate lines can conflict with the opposite goal. Fields that the same thread uses together should share a line. So the rule is to group by thread, then separate by thread.
False sharing also depends on the allocator and on the platform. A layout that works on one machine can fail on another if line size or allocation alignment differs. Test on the hardware you deploy to.
Detecting it
False sharing does not show up as a bug. It shows up as poor scaling: adding threads makes the program slower, or no faster. These signs suggest it:
- Throughput drops when you go from one thread to two, with no lock contention.
- Time per operation changes when you reorder unrelated struct fields.
- Profilers show high time on simple stores or atomic operations.
On Linux, perf c2c records cache-to-cache transfers and reports which cache lines are contended and which fields in them different threads access. Hardware counters for "HITM" events (a load that hits a line modified in another core's cache) also point to it. Intel VTune has a similar analysis. As always, confirm with a before and after benchmark. Pad the suspected data and check that the time drops.
Exercise
A program has struct Stats { long reads; long writes; }; and Stats stats[8];, where thread i updates only stats[i]. Each struct is 16 bytes and the line size is 64 bytes. Adding threads makes the program slower. Why, and what is the smallest change that fixes it?
Show answer
Four Stats elements fit in each 64-byte line, so up to four threads write to the same line and keep invalidating each other's copy. This is false sharing. The smallest fix is to declare the struct struct alignas(64) Stats { long reads; long writes; };. The compiler then pads each element to 64 bytes, so each thread owns a separate line. Accumulating in thread-local variables and writing the result once also works and uses less memory.
Exercise
Two threads only read a shared configuration struct, and a third thread writes a counter that sits right after it in the same cache line. Do the two reading threads suffer from false sharing? Explain.
Show answer
Yes. Reads alone are cheap because the line can sit in the Shared state in many caches. But each write by the third thread invalidates the other cores' copies, so the readers must fetch the line again after every write. Moving the counter to its own line, for example with alignas(64), removes the problem.