IT lexicon › Programming › Memory fence

Memory fence Memory barrier

Programming På svenska → Updated: 2026-07-29

An instruction constraining how memory operations may be moved around it. Needed because both the compiler and the processor reorder things behind your back.

The reordering is invisible in single-threaded code — the result is the same — and devastating in multi-threaded code. The classic bug is publishing a pointer to an object before the object's fields have become visible to another core, which then reads rubbish out of an object that from its point of view was never initialised. Fences come in variants matching the memory orderings: an acquire fence stops later reads moving forward, a release fence stops earlier writes moving back, and a full fence stops everything. Two things surprise people. Compiler reordering and hardware reordering are separate problems and both must be handled, which is why volatile is not a threading tool. And x86's strong ordering means incorrect code often works there and breaks on ARM.

← Back to the lexicon