We use memory_order
as an argument in functions that require atomic operations to occur. It specifies how operations on distinct threads are
The compiler or CPU can reorder memory access. They can execute in different orders when a separate thread tries to communicate, as well as observe a hierarchy of memory access that breaks the
To overcome this, we use the memory_order
memory_order
determines the order of memory accesses for an atomic operation even for regular, non-atomic memory accesses.
memory_order
constantsThe memory_order
enum has multiple constants with specified usages.
memory_order_relaxed
: this type of atomic operation can have various optimizations performed on them, and they do not guarantee an order concerning locking and normal memory accesses.
memory_order_acquire
: this prevents ordinary loads and stores from being reordered before the atomic operation.
memory_order_consume
: this performs the same operation as memory_order_acquire
, except that the ordering guarantees only apply to dependent data.
memory_order_release
: this prevents ordinary loads and stores from being reordered after the atomic operation.
memory_order_acq_rel
: this is a hybrid of memory_order_acquire
and memory_order_release
. Unlike the sequentially consistent model, this hybrid applies a happens-before relationship to dependent variables. This variant allows the synchronization requirements between independent readings and writes to be relaxed.
memory_order_seq_cst
: this operates when all access to memory (that may have visible side effects on the other threads involved) has already happened. This is the strictest memory order variant. Thus, it guarantees the most negligible unexpected side effects between the thread interactions through non-atomic memory accesses.
Note:
memory_order
operations in C are specified by including a built-in library<stdatomic.h>
in the code file.
Free Resources