Separate variables can still share coherence traffic
Two threads can update different variables while those variables occupy the same cache-coherence unit. Ownership changes and invalidations can then make otherwise independent updates interfere; this is false sharing. Compare adjacent counters with counters spaced farther apart, keeping increment counts equal. Use atomic updates so the comparison does not depend on a C data race or undefined behavior. The program targets Linux with GCC-compatible builtins and pthreads and is compiled as C11. Layout changes affect the experiment’s own objects only, not host cache or CPU settings. The mechanism concerns storage placement and coherence, rather than two threads intentionally communicating through the same logical counter.
Inspect spacing as well as both final values
The adjacent case uses the first two elements of an array aligned to 128 bytes. The spaced case places counters in separate structures each requiring 128-byte alignment. The chosen spacing is an experiment parameter, not a claim that every machine has a 128-byte cache line. Print the actual address difference to inspect the resulting layout. Each worker performs one hundred thousand increments, and both final values must match that count. This prevents a missing workload from being mislabeled as a speed improvement. Compile with cc -std=c11 -O2 -Wall -Wextra -Werror -pthread. Inspect compilation errors rather than removing the assertions or silently changing the operation to make a comparison appear successful.
#define _POSIX_C_SOURCE 200809L
#include <assert.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <time.h>
struct adjacent { _Alignas(128) unsigned long value[2]; };
struct slot { _Alignas(128) unsigned long value; };
struct job { unsigned long *value; };
static void *work(void *arg) {
struct job *j = arg;
for (unsigned i = 0; i < 100000; ++i)
__atomic_fetch_add(j->value, 1UL, __ATOMIC_RELAXED);
return NULL;
}
static void run(const char *name, unsigned long *a, unsigned long *b) {
pthread_t threads[2]; struct job jobs[2] = {{a}, {b}};
struct timespec begin, end;
assert(clock_gettime(CLOCK_MONOTONIC, &begin) == 0);
for (unsigned i = 0; i < 2; ++i)
assert(pthread_create(&threads[i], NULL, work, &jobs[i]) == 0);
for (unsigned i = 0; i < 2; ++i)
assert(pthread_join(threads[i], NULL) == 0);
assert(clock_gettime(CLOCK_MONOTONIC, &end) == 0);
assert(*a == 100000UL && *b == 100000UL);
double seconds = (end.tv_sec - begin.tv_sec) + (end.tv_nsec - begin.tv_nsec) / 1e9;
printf("%s spacing=%lu count=%lu/%lu seconds=%.6f\n", name,
(unsigned long)((uintptr_t)b - (uintptr_t)a), *a, *b, seconds);
}
int main(void) {
struct adjacent close = {{0, 0}};
struct slot spaced[2] = {{0}, {0}};
run("adjacent", &close.value[0], &close.value[1]);
run("spaced", &spaced[0].value, &spaced[1].value);
return 0;
}Do not require one timing order as a pass condition
The expected coherence effect may be weak when workers do not run simultaneously on different cores. Thread startup, CPU sharing, frequency changes, scheduling and actual coherence granularity also affect elapsed time. Do not assert that spacing must win. Repeat and alternate execution order, retaining every observation. A deeper dedicated experiment can investigate CPU placement and relevant performance counters. The present measurement includes worker creation through joining, so it is not the isolated cost of increment instructions. Apply any revised measurement boundary equally to both cases. Correct counts and inspected layout are pass conditions; a particular relative runtime remains a workload-and-host observation requiring its own interpretation.
Padding has storage and locality costs
Spacing small counters consumes more memory for the same number of logical values. At scale this can increase cache-capacity and translation pressure. Conversely, closely placed values can improve locality when one thread often reads them together. Distinguish frequently contended writes from data intentionally accessed as a group. Making a structure larger is not by itself evidence that an application bottleneck has been fixed. Trace which threads access which fields and when, then relate their placement to the machine’s sharing granularity. An optimization for one access pattern can make another pattern worse, so compare the relevant read, write and memory-footprint consequences instead of treating padding as an unconditional best practice.
Use observations to choose the next hypothesis
Retain both counter values, address spacing, elapsed seconds, compiler settings and execution conditions. A large difference can motivate a false-sharing hypothesis, but timing alone does not prove the cause. A small difference does not disprove false sharing generally. Investigate actual core placement, generated operations and unrelated shared data that might enter the comparison. The program remains a small bounded workload rather than increasing iterations indefinitely or changing host-wide settings to obtain a dramatic result. Applying a layout change to a service requires separate assessment of end-to-end response time and memory-footprint costs. A micro-experiment should inform that investigation without claiming a universal production speedup.