← Lessons

quiz vs the machine

Platinum1810

Concurrency

The Fences and Barriers Deep Dive

Standalone ordering instructions and how they differ from atomic operations.

6 min read · advanced · beat Platinum to climb

Ordering without a value

A fence, also called a memory barrier, is an operation that restricts reordering of memory accesses around it without itself reading or writing a shared location. Where acquire release attach ordering to a specific atomic access, a fence is a standalone ordering point.

Kinds of fences

Hardware and languages expose several flavors, conceptually controlling which pairs of access types may cross.

  • A load load or acquire fence stops later loads from moving above it.
  • A store store or release fence stops earlier stores from moving below it.
  • A full fence orders all access types in both directions and is the most expensive.

Fence versus atomic order

A standalone fence can be paired with relaxed atomic operations to recreate acquire release semantics, which is useful when you want one fence to order several accesses at once rather than tagging each. The tradeoff is that fences are coarser: they order everything of the relevant kind, not just one variable, so they can be heavier than a targeted acquire or release.

Key idea

A fence is a standalone barrier that orders classes of memory accesses around it, and combined with relaxed atomics it can substitute for per operation acquire release at a coarser granularity.

Check yourself

Answer to earn rating on the learn ladder.

1. How does a fence differ from an acquire or release operation?

2. What is a downside of a fence versus a targeted acquire or release?