core22 min studyLesson 115 in Engineering

False sharing and ownership-aware layout

Identify independent fields that interfere through shared cache-line ownership, then evaluate padding as a measured tradeoff.

On this page

What you’ll understand

  • Distinguish true sharing from false sharing.
  • Calculate the storage consequences of an explicitly aligned layout.
  • Design evidence that separates coherence traffic from unrelated bottlenecks.

Two workers can update logically independent counters and still interfere because the counters occupy one coherence block. The application shares no counter value, but the hardware must coordinate permission to modify the containing line. This is false sharing. The important question is not simply whether fields are adjacent: ask which cores access them, which accesses write, and how frequently those accesses make ownership move between cores.

Independence in the program is not separation in the cache

Place two independent counters in the same line and assign one writer to each. If both cores repeatedly write, permission for the line can pass back and forth even though neither core needs the other's counter. A read-only field beside a frequently updated field can also suffer invalidations. By contrast, two cores reading an unmodified line do not create the same write-ownership conflict merely because their data share storage. The access pattern supplies the harmful interaction.

True sharing means threads communicate through the same logical data, such as updating one common total. Padding cannot remove that dependency. False sharing means the coherence granularity is larger than the independent pieces of application state. Both can occur in one structure, and fixing one can expose the other. Inspect actual field offsets and alignment in the built program instead of inferring layout from source declaration order or an allocator's usual behavior.

⌊aL⌋=⌊bL⌋\left\lfloor\frac{a}{L}\right\rfloor=\left\lfloor\frac{b}{L}\right\rfloor
For nonnegative byte addresses a and b in a simple L-byte line layout, equality means the addressed bytes occupy the same line. L is declared hardware geometry; the equality alone does not prove harmful false sharing without a concurrent access pattern including writes.↔ Scroll wide equations horizontally.

Padding trades density for separation

An aligned per-worker record can place independently written state on separate lines. Both record size and starting alignment matter. Adding a few unused bytes without verifying boundaries may merely move the conflict elsewhere. In portable code, use a layout abstraction appropriate to the language and target platform, and confirm its compiled representation. Keep deliberately shared control fields separate from per-worker payloads when their ownership patterns differ, rather than blindly padding every scalar.

The cost is larger live storage, more lines, and potentially more translations and memory traffic. A dense read-mostly scan may become slower when padding expands its footprint. Aggregating local counters periodically can reduce writes to a common total, but readers then observe a different freshness contract unless synchronization supplies an exact snapshot. A performance change is valid only if it preserves the application's required accuracy, visibility, and ownership rules.

Ddense=Ns,Dseparated=NL(s≤L)D_{\rm dense}=Ns,\qquad D_{\rm separated}=N L\quad(s\leq L)
For N records each holding s bytes, the dense payload is Ns bytes. A deliberately L-aligned, L-byte slot per record occupies NL bytes, assuming each record fits in one slot. The second value includes unused slot space and describes a chosen layout, not a universal padding rule.↔ Scroll wide equations horizontally.

Use a controlled ownership experiment

Compare dense and separated variants with identical atomic operations, worker count, useful updates, and aggregation behavior. Bind workers deliberately if the experiment requires stable placement, and document whether they share a core, cache, or socket. A cache-to-cache analysis tool may identify a hot line and accessing instructions; verify that their addresses correspond to the independent fields. An ordinary last-level miss total cannot uniquely diagnose false sharing, and a speedup alone cannot identify the coherence transition involved.

The function lab provides a limited arithmetic sensitivity check with y=ax². Hold positive x fixed and increase positive a to represent a larger normalized per-record footprint for a square worker-by-bucket table. Predict the linear change with a. It does not show invalidations, ownership handoffs, or processor timing. Use the readout only to examine the storage side of a padding choice, then explain what an actual ownership trace would have to establish about the performance side.

Four counters and four ownership domains

Four workers each update one eight-byte atomic counter. All counters initially occupy a single aligned 64-byte line. A proposed layout gives each counter a separate aligned 64-byte slot.

  1. The useful counters contain 4×8=32 bytes, and the declared dense arrangement fits within one 64-byte coherence block. Independent writes can therefore interfere at line granularity.

  2. The separated arrangement occupies 4×64=256 bytes of slots, with 224 bytes not used by the counter payloads. Its slot footprint is eight times the 32-byte useful payload, and four times the original single-line occupied span.

  3. Run both with the same number and kind of increments. Look for changed cache-to-cache ownership traffic and elapsed time. Separation removes this particular same-line relation but does not remove atomic instruction cost, scheduling effects, or later contention on aggregation.

The result

Padding changes which independent writers compete for a line at a clear space cost. No fixed speedup follows from the byte calculation.

Explore the model

Interactive lab

Interactive lab · function

The footprint side of padding

Explore y=ax² with positive x and a. Hold x fixed and increase a to represent a larger normalized per-cell footprint in a square table. This is storage arithmetic, not a coherence or false-sharing simulation.

The footprint side of paddingThis lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Current readings: y at chosen x: 0.608; Tangent slope · 2ax: 1.35; Signed area · ax³/3: 0.182. All parameters are adjustable with the labeled controls below.−2.4−1.201.22.4−9−4.504.59xy(x, ax²)
y = ax²TangentSigned integral
y at chosen x
0.608
Tangent slope · 2ax
1.35
Signed area · ax³/3
0.182
t = 0 s

This lab uses only y = ax². Playback traces the curve within the fixed integration interval from 0 to x; it does not estimate numerical error or change the chosen point. Parameter changes pause playback and recompute the model at the current elapsed time. Reset restores both parameters and returns time to zero. Playback starts paused. Adjust either parameter, then choose Play or Step.

Look forA layout optimization can spend substantial memory even when its ownership benefit is real.

Check your understanding

Which pattern most directly establishes a false-sharing candidate?

Try it yourself

Eight 16-byte worker records are packed into two aligned 64-byte lines. Each worker writes only its own record. Compute the occupied slot footprint if every record receives a separate aligned 64-byte slot, and name one workload that could lose from the change.

Take a moment to make a prediction or work it out on paper. Open a hint when you need one.

Give me a hint

Separate useful payload from allocated slots and consider a later scan over all workers.

Compare with the solution

Dense payload and span are 8×16=128 bytes. Separate slots occupy 8×64=512 bytes, four times as much. A frequent read-only scan of all records may transfer more lines and suffer worse locality. Measure the update and scan phases together under the required publication semantics rather than optimizing only the parallel increments.

Take it with you

  • False sharing couples independent data through coherence-block granularity.
  • Padding requires verified alignment and has a real footprint cost.
  • Ownership evidence and unchanged synchronization semantics are essential to a valid comparison.

Read further

Original sources and deeper explanations to follow at your own pace.

Optional progress, saved in this browser when available. Revisit any lesson at any time.

Lesson not marked complete.