false-sharing
Table of Contents
False sharing
False sharing is a performance bug where two threads modify logically unrelated variables that fall on the same cache line, causing the coherence protocol to bounce the line back and forth between cores as if they were contending for the same data. Nothing is functionally wrong—each thread only touches its own variable—but cache-line granularity creates artificial contention.
Fix false sharing by padding fields to separate cache lines or using std::hardware_destructive_interference_size for portable alignment.
Example
This example demonstrates false sharing by measuring throughput with and without padding.
// compile: gcc -std=c11 -pthread -O2 -o falseshare falseshare.c // run: ./falseshare // description: show false sharing causing unnecessary cache line bouncing #include <stdio.h> #include <pthread.h> #include <stdatomic.h> #include <time.h> #define ITERATIONS 10000000 #define CACHE_LINE_SIZE 64 struct counters_shared { atomic_int a; atomic_int b; }; struct counters_padded { atomic_int a; char pad[60]; atomic_int b; }; void* increment_shared(void* arg) { struct counters_shared* c = (struct counters_shared*)arg; for (int i = 0; i < ITERATIONS; i++) { atomic_fetch_add(&c->b, 1); } return NULL; } int main() { struct counters_shared shared = {0, 0}; pthread_t t1, t2; clock_t start = clock(); pthread_create(&t1, NULL, increment_shared, &shared); pthread_create(&t2, NULL, increment_shared, &shared); pthread_join(t1, NULL); pthread_join(t2, NULL); clock_t end = clock(); printf("Time with false sharing: %ld cycles\n", end - start); printf("Final count: %d (expected %d)\n", atomic_load(&shared.b), ITERATIONS * 2); return 0; }
false-sharing.md · Last modified: by 127.0.0.1
