OSC++.042: False Sharing and Cache-Line Contention in C++

Colored-pencil illustration of an exposed processor die on a laboratory mat.

Open Source C++ Programming · Super-Fundamental (042) · 35–45 minutes

Two workers can update different counters without a data race and still make each other slower. Hardware typically maintains coherence over blocks of memory called cache lines, not one C++ object at a time. Adjacent counters can end up inside the same line. The previous lesson used latches and barriers to coordinate workers; here the barrier aligns the start of the example without fixing the data layout.

What you will learn

Identify a plausible false-sharing layout, distinguish correctness from contention, and verify a proposed separation with object offsets. You should already be comfortable with starting and joining C++ threads and basic atomic operations. Use a C++20 compiler from a local, authorized development environment. The example assumes a 64-byte boundary for illustration rather than detecting the current processor’s hardware line size.

Why separate variables can contend

A cache line is a unit of transfer and coherence. If two cores repeatedly write to different locations in the same line, a core that needs to modify that line can force a coherence exchange with another core. The updates do not logically share a counter. They do share a hardware unit. With true sharing, the workers access a value that is actually shared; padding cannot separate two writes to the same counter.

An Intel Core i7-920 processor with its heat spreader removed, exposing the silicon die
An exposed Intel Core i7-920 die provides physical context for a multicore processor. The photograph does not identify individual cache lines or depict the tested hardware. Fritzchens Fritz, CC0.
Valigo’s demonstration introduces cache lines around 4:23 and shows how to inspect their addresses around 20:29.

A race-free program is not necessarily a fast one. Conversely, separating fields does not repair a data race. Atomic operations still need to meet the program’s synchronization requirements. An independently updated counter can use relaxed ordering when it does not communicate readiness or publish other data. The release/acquire lesson explains why that choice does not transfer to a readiness flag.

Inspect the layout first

The adjacent struct begins at a 64-byte boundary. Its two counters are checked at compile time to fit within the first 64 bytes. Each separated slot has a 64-byte alignment requirement, and the second slot starts at least 64 bytes into the object. The C++ draft’s interference-size provision defines std::hardware_destructive_interference_size as an implementation-defined recommended separation. The value chosen by your toolchain is not proof of the physical line size on every deployment target.

The example keeps the same operation count and atomic operation in both runs. Joining the workers before reading their totals is the completion boundary. The relaxed increments keep each counter atomic without making either counter a signal for other memory. The earlier std::packaged_task lesson shows a different approach, where a worker returns its result instead of updating a counter for each operation.

#include <atomic>
#include <barrier>
#include <cstddef>
#include <cstdint>
#include <iostream>
#include <thread>

using Raw = std::uint64_t;
using Counter = std::atomic<Raw>;
constexpr auto relaxed
    = std::memory_order_relaxed;
constexpr auto assumed_line = 64;
constexpr std::uint64_t increments
    = 100000;

struct alignas(assumed_line) Adjacent {
    Counter a{0};
    Counter b{0};
};
struct alignas(assumed_line) Slot {
    Counter value{0};
};
struct Separated {
    Slot a;
    Slot b;
};

static_assert(
    offsetof(Adjacent, b)
    + sizeof(Counter) <= assumed_line
);
static_assert(
    offsetof(Separated, b)
    >= assumed_line
);

void run(
    const char* name,
    Counter& a, Counter& b
) {
    std::barrier gate(3);
    auto increment =
        [&](Counter& target) {
            gate.arrive_and_wait();
            for (Raw i = 0;
                 i < increments; ++i) {
                target.fetch_add(
                    1, relaxed);
            }
        };
    std::jthread first([&] {
        increment(a);
    });
    std::jthread second([&] {
        increment(b);
    });
    gate.arrive_and_wait();
    first.join();
    second.join();
    std::cout << name << ": "
        << a.load(relaxed)
        << ' '
        << b.load(relaxed)
        << '\n';
}

int main() {
    Adjacent adjacent;
    Separated separated;
    run("adjacent", adjacent.a,
        adjacent.b);
    run("separated", separated.a.value,
        separated.b.value);
    std::cout
        << "second-counter offsets: "
        << offsetof(Adjacent, b)
        << ' '
        << offsetof(Separated, b)
        << " bytes\n";
}

Save as counters.cpp. Build and run it from a terminal:

g++ -std=c++20 -O2 -pthread \
  -Wall -Wextra -Werror -pedantic \
  counters.cpp -o counters
./counters

Observed output for the tested compiler and layout. Offsets can vary by target; each counter should still reach 100,000:

adjacent: 100000 100000
separated: 100000 100000
second-counter offsets: 8 64 bytes

Troubleshoot before optimizing

The example measures no speed. Same-line writes may behave differently depending on whether workers run on separate physical cores, how the CPU implements atomic operations, and whether the program stays in the same socket. Padding can also increase memory footprint. When profiling your own code, compare only one change at a time, record the compiler and CPU, and repeat both layouts under the same workload. The Linux kernel’s false-sharing guide discusses cache-to-cache measurements and identifying contended lines. Respect host profiling permissions rather than changing system-wide settings for a lesson.

A practical alternative is to keep a plain counter local to each worker and combine the totals after joining. That removes repeated writes to shared storage during the loop. It works only when consumers do not need continuously updated totals.

Egor Garbuz’s LinkedIn post opens by describing a false-sharing demonstration that did not behave as expected.
Egor Garbuz’s experiment illustrates why the loop’s exact operation matters: the difference he saw depended on whether the loop used an atomic read-modify-write or plain loads and stores. His benchmark results describe his setup, not a guaranteed speed difference. Cropped source screenshot.

Exercises and answers

Exercise: On the example target, which offsets can fall in the same 64-byte interval: 0 and 8, or 0 and 64? Would changing relaxed ordering to sequentially consistent ordering separate them?

Answer: Offsets 0 and 8 are in the same interval. Offset 64 starts the next interval on the assumed boundary. Ordering constraints do not change where an object is placed.

Exercise: Replace the atomic increments with worker-local counts and a single write to each worker’s own result slot. Can the main thread read those plain results before joining?

Answer: No, not without another synchronization mechanism. Each worker can write a separate result slot, but the main thread should wait for both joins before reading the plain results.

Editor’s Note: We volunteer daily to ensure the credibility of the information on this platform is Verifiably True.

BitcoinVersus.Tech publishes technology and financial journalism for informational purposes and does not provide financial, investment, or legal advice.

One response to “OSC++.042: False Sharing and Cache-Line Contention in C++”

  1. […] warm-up and deployment overhead can also change the economics of a short-lived service. Our cache-line contention lesson and MLPerf Client analysis offer complementary examples of choosing the right measurement. The […]

    Like

Leave a Reply