Detect false sharing with a runnable C benchmark
Compare adjacent atomic counters with cache-line-separated counters, then use perf c2c to locate contended lines when PMU access is available.
If independent counters slow down when two cores update them, test whether they occupy the same cache line. Keep the algorithm and atomic ordering identical, separate the storage, and measure again. False sharing happens when cores exchange ownership of a line even though they modify different variables; a data race is not required.
Run the adjacent and padded versions
Save as false-sharing.c. This Linux example pins its workers to CPUs 0 and 2, which are different physical cores on the test machine. Check your affinity mask and topology with lscpu -e=CPU,CORE,SOCKET; choose two permitted cores before running elsewhere.
#define _GNU_SOURCE
#include <pthread.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <sched.h>
static _Alignas(64) atomic_ulong packed[2];
struct slot { _Alignas(64) atomic_ulong value; };
static struct slot padded[2];
static pthread_barrier_t barrier;
struct job { atomic_ulong *counter; int cpu; };
static void *work(void *arg) {
struct job *j = arg;
cpu_set_t set; CPU_ZERO(&set); CPU_SET(j->cpu, &set);
if (pthread_setaffinity_np(pthread_self(), sizeof set, &set)) abort();
pthread_barrier_wait(&barrier);
for (unsigned i = 0; i < 20000000; i++)
atomic_fetch_add_explicit(j->counter, 1, memory_order_relaxed);
return NULL;
}
static double now(void) {
struct timespec t; clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec + t.tv_nsec / 1e9;
}
int main(void) {
for (int pad = 0; pad < 2; pad++) {
pthread_t threads[2];
struct job jobs[2] = {{pad ? &padded[0].value : &packed[0], 0},
{pad ? &padded[1].value : &packed[1], 2}};
pthread_barrier_init(&barrier, NULL, 3);
for (int i = 0; i < 2; i++)
if (pthread_create(&threads[i], NULL, work, &jobs[i])) abort();
double start = now();
pthread_barrier_wait(&barrier);
for (int i = 0; i < 2; i++) pthread_join(threads[i], NULL);
printf("%s %.3f s; counters %lu %lu\n", pad ? "padded" : "packed",
now() - start, atomic_load(jobs[0].counter), atomic_load(jobs[1].counter));
pthread_barrier_destroy(&barrier);
}
}
gcc -O2 -g -std=c11 -Wall -Wextra -Werror -pthread false-sharing.c -o false-sharing
./false-sharing
Example timings on a 13th Gen Intel Core i7-1355U, GCC 15.2, Linux:
packed 0.884 s; counters 20000000 20000000
padded 0.174 s; counters 20000000 20000000
Treat these timings as an example measurement, not a portable speedup promise. Thermal state, competing work and core topology matter; repeat the comparison under your workload.
Both versions perform 20 million relaxed atomic increments per worker and finish with the same counts. Relaxed ordering removes unnecessary ordering requirements; it does not remove coherence traffic. Alignment of the structure also rounds its size to an alignment multiple, so consecutive padded elements begin on separate 64-byte boundaries. Here 64 matches the CPU’s cache-line size; it is a measured platform assumption, not a universal constant. The barrier makes both workers start their loops together.
Locate the line with perf c2c
perf c2c record -- ./false-sharing
perf c2c report --stdio
On supported hardware, start at the shared-line table and sort your attention toward high local/remote HITM counts. HITM indicates a sampled access involving a modified line in another cache. Expand a line to inspect offsets, instruction addresses and participating CPUs. Different hot field offsets in one line suggest false sharing; the same offset may indicate intentional sharing. Sampling does not capture every transfer. The perf c2c manual documents the report and architecture-dependent PMU requirements.
If recording fails with a permission error, inspect cat /proc/sys/kernel/perf_event_paranoid and your system’s perf access policy. A restrictive setting such as 4 can block PMU access. Use an environment whose policy permits profiling; missing hardware support or denied access does not establish that contention is absent. Timings alone show a layout-sensitive slowdown, while a c2c profile can identify the contended line.
Choose the smallest fix
Separate frequently written fields owned by different threads, shard counters, or aggregate locally and publish less often. Padding every field increases working-set size and can hurt readers. The kernel false-sharing guide discusses inspecting actual layouts before changing them.
Go deeper
Read atomic coherence for ownership transfers and memory caches for the line-sized unit behind the effect.