Every program you write runs in a world that looks sequential — one instruction after the next, in the order you wrote them. That illusion is carefully maintained, but only for a single thread.
The moment two threads share a variable, the deal changes. Modern CPUs execute instructions out of order to keep their pipelines busy, and compilers reorder stores and loads to reduce memory traffic. Each thread still sees a consistent view of its own operations, but what another thread observes can look scrambled in time.
A memory barrier (also called a memory fence) is an instruction that says: "every load and store before me must complete before any load or store after me begins." It is the only portable tool that puts time back in order across cores.
The subject sits at the intersection of hardware microarchitecture and the correctness of concurrent programs. Getting it wrong produces bugs that appear once in a million runs — and vanish the moment you add a print statement to debug them.
Comments
Loading comments...