I am trying to understand what is a memory barrier exactly.
Based on what I know so far, a memory barrier (for example: mfence
) is used to prevent the re-ordering of instructions from before to after and from after to before the memory barrier.
This is an example of a memory barrier in use:
instruction 1
instruction 2
instruction 3
mfence
instruction 4
instruction 5
instruction 6
Now my question is: Is the mfence
instruction just a marker telling the CPU in what order to execute the instructions? Or is it an instruction that the CPU actually executes like it executes other instructions (for example: mov
).
std::atomic_signal_fence()
or GNU Casm("":::"memory")
are purely markers in the source code, and compile to zero instructions. They exist to block reordering at compile time, and are especially useful when the target architecture has a stronger memory model than the source language (e.g. C++ -> x86 asm). preshing.com/20120625/memory-ordering-at-compile-time explains more. – Elfin