Skip to content
systemcoding.dev
Performance

False Sharing Explained With a Counter Benchmark

False sharing makes threads that write different variables slow each other down because they share a cache line. See it in a four-thread C counter.

6 min read
Summarize in AI
Flat illustration of a CPU core with its cache levels and main memory, with the C, C++ and Arm logos.

You split a job across four threads. Each thread increments its own counter, no locks, no shared data, nothing to wait for. You expect four times the speed. The program runs slower than the single-threaded version. This is false sharing, and it is the most common way a correct multithreaded program turns out slow. This post explains what it is from the ground up, builds a four-thread counter benchmark in C with POSIX threads, and shows the layout that makes the problem appear and the one that removes it. It assumes only that you can read C. The code builds with gcc 13 on Linux, with -O2 -pthread, and the explanations of the cache hardware follow the earlier posts in this series.

What a cache line is, in one paragraph

The processor does not read single bytes from memory into its cache. It reads fixed-size blocks called cache lines, which are 64 bytes on x86-64 and most Arm chips. If you touch one byte, the whole 64-byte block containing it is loaded. This is usually helpful: the neighbours of what you touched are probably needed next. Here it becomes a problem.

What "sharing" means to a CPU

Each core has its own private cache. When two cores both hold a copy of the same line, the hardware must keep the copies consistent. If one core writes to its copy, the other core's copy is out of date, so the hardware invalidates it. The other core's next access then has to fetch the line again. The rule that governs this, the MESI protocol covered in an earlier post, works on whole lines, not on individual variables.

That is the key fact. The hardware does not know that your two counters are separate variables. It sees two writes to the same line. So if thread 1 writes counter A and thread 2 writes counter B, and A and B sit in the same 64-byte line, the line ping-pongs between the two cores: each write invalidates the other core's copy. Nothing is logically shared, yet physically they fight over one line. That is false sharing: sharing that exists in the hardware and not in your program.

The benchmark

Here is a program with four threads, each incrementing its own counter ten million times. The counters are in an array of long.

shared_counters.cc
#include <pthread.h>
#include <stdio.h>

#define THREADS 4
#define ITERATIONS 10000000L

static volatile long counters[THREADS];

static void *worker(void *arg)
{
    long id = (long)arg;
    for (long i = 0; i < ITERATIONS; i++)
        counters[id]++;
    return NULL;
}

int main(void)
{
    pthread_t t[THREADS];
    for (long i = 0; i < THREADS; i++)
        pthread_create(&t[i], NULL, worker, (void *)i);
    for (int i = 0; i < THREADS; i++)
        pthread_join(t[i], NULL);

    long total = 0;
    for (int i = 0; i < THREADS; i++)
        total += counters[i];
    printf("total = %ld\n", total);
    return 0;
}
Text
total = 40000000

The answer is correct, since each thread has its own element and writes only to it. The volatile keyword forces every increment to go to memory, which keeps the compiler from holding the count in a register for the whole loop and hiding the effect. Without it, an optimising compiler would keep counters[id] in a register and write once at the end, and there would be nothing to see.

The four counters take 32 bytes, 8 bytes each, so they all sit in a single cache line. Every thread is writing to the same line. The line bounces among four cores for forty million increments. Build and time it:

Shell
gcc -O2 -pthread shared_counters.c -o shared_counters
time ./shared_counters

The runtime on a four-core machine is typically no better than the single-thread run of the same total work, and often worse, though the exact figures depend on your processor and we do not quote any here. If you want to see the line moving, perf stat -e cache-misses or the perf c2c tool, which looks for exactly this pattern, will show the contention.

The fix: one line per counter

Give each counter its own cache line by padding, so no two threads write the same line.

padded_counters.cc
#include <pthread.h>
#include <stdio.h>

#define THREADS 4
#define ITERATIONS 10000000L

struct padded {
    volatile long value;
    char pad[64 - sizeof(long)];
};

static struct padded counters[THREADS] __attribute__((aligned(64)));

static void *worker(void *arg)
{
    long id = (long)arg;
    for (long i = 0; i < ITERATIONS; i++)
        counters[id].value++;
    return NULL;
}

int main(void)
{
    pthread_t t[THREADS];
    for (long i = 0; i < THREADS; i++)
        pthread_create(&t[i], NULL, worker, (void *)i);
    for (int i = 0; i < THREADS; i++)
        pthread_join(t[i], NULL);

    long total = 0;
    for (int i = 0; i < THREADS; i++)
        total += counters[i].value;
    printf("total = %ld\n", total);
    printf("sizeof(struct padded) = %zu\n", sizeof(struct padded));
    return 0;
}
Text
total = 40000000
sizeof(struct padded) = 64

Each struct padded is exactly 64 bytes, and the array is aligned to 64, so each element starts on a line boundary and owns its line completely. Thread 0 writes line 0, thread 1 writes line 1 and so on. No two threads write the same line, so no invalidations pass between the cores, and each increment hits in its own core's L1. The same arithmetic, same result, and the program scales with the thread count.

The padding costs memory: 64 bytes per counter instead of 8, a factor of 8. For four counters it is nothing. For an array of a million per-thread slots it would matter, and the post on sharding counters later in this series shows how to keep that small.

How to know you have it

The symptom is a multithreaded program that gets slower, or gets no faster, when you add threads, with no lock in sight. Three checks confirm it.

Run the program with one thread and then with four. If four threads take as long as one for four times the work, or longer, suspect contention on a line. Look at what the threads write. If they write adjacent elements of an array, or fields of the same struct, or separate variables that the compiler placed next to each other, they may share lines. And run perf c2c record then perf c2c report, which reports lines with a high count of cross-core modified accesses, called HITM in its output, and shows the offsets within the line that each thread touched. The post on detecting false sharing with perf c2c goes through it.

A quick experiment helps too: add padding and see whether the speed changes. If it does, you had false sharing.

Where it hides in real code

The benchmark is deliberate, and real programs hide it better. Per-thread statistics stored in a global array indexed by thread ID, with an int or long per thread, are the classic case. Queue indices, a head written by the consumer and a tail written by the producer, in one struct, are another. Locks themselves: an array of mutexes of 40 bytes each puts two or three in a line, so threads taking different locks still bounce the line. A struct with a hot read-mostly field next to a frequently written field, so every write invalidates the readers. And object pools or arrays of small objects, each owned by a different thread.

The cure is always the same: separate what different threads write by at least a cache line. The cost is memory, and sometimes readability.

What not to pad

Do not pad data that is only read. Many threads reading the same line is fine, since a Shared copy in each cache needs no invalidation until someone writes. Do not pad everything defensively either, since padding wastes cache capacity and makes each counter touch its own line, which is bad if one thread updates many counters. Pad the variables that different threads write often.

Share

Keep reading

Flat illustration of two options weighed side by side, with the C, C++ and Rust logos.
Performance

Spinlocks vs Mutexes: When Spinning Wins

A spinlock burns a core while it waits and a mutex sleeps. Compare their costs, write a correct C11 spinlock, and see when user-space spinning beats a mutex.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.