← Lessons

quiz vs the machine

Platinum1790

Concurrency

Padding To Avoid Contention

Aligning hot variables to separate cache lines to stop false sharing.

5 min read · advanced · beat Platinum to climb

Padding To Avoid Contention

Once false sharing is identified, the standard cure is padding. You add unused bytes around each hot variable so that no two of them land on the same cache line, giving each its own line that no other core needs to touch.

The technique aligns a variable to a cache line boundary and pads its containing structure up to a full line, commonly sixty four bytes. After padding, when core A writes its variable, the invalidation no longer disturbs core B because B works on a different line entirely. The ping pong disappears.

  • Trades memory for speed Each padded variable now costs a full line, but the contention vanishes.
  • Per thread data Arrays of per thread counters benefit most, pad each slot to its own line.
  • Verify with measurement Padding helps only when false sharing was the real problem, so confirm with a profiler.

There is a subtlety. Padding the structure is not enough if the allocator places several padded objects adjacently in a way that still straddles a line, so alignment to the line boundary matters too. Done right, padding turns a contended hot path into a clean parallel one.

Key idea

Padding hot variables to a full cache line each gives every core its own line, eliminating the false sharing ping pong at the cost of memory.

Check yourself

Answer to earn rating on the learn ladder.

1. What does padding a hot variable accomplish?

2. What is the main cost of padding to avoid contention?