Home / Forums / How does std::atomic memory_order_relaxed differ from memory_order_seq_cst? [Discussion #9]

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

How does std::atomic memory_order_relaxed differ from memory_order_seq_cst? [Discussion #9]

MatrixRecon
3D Math & Vectors
MEMBER
Rep: 225
Join Date: Jan 2025
Posts: 33
Thanks: 55
1y ago · Nov 22, 2024 5:42 PM
#1
Can someone explain the real-world difference between memory_order_relaxed and the default memory_order_seq_cst in C++ atomics? When is relaxed safe to use?
MatrixRecon · 3D Mathematics & View Matrix Calculations
The following users thanked MatrixRecon for this post:
VMT_Hooker
VMT / Detours Engineer
VIP
Rep: 310
Join Date: Mar 2023
Posts: 22
Thanks: 80
1y ago · Nov 22, 2024 7:59 PM
#2
memory_order_seq_cst enforces a globally consistent execution order across all CPU cores with hardware memory barriers. memory_order_relaxed guarantees atomicity of the single variable itself, but permits the CPU and compiler to reorder surrounding reads and writes! Use relaxed for independent counters or flags where no other memory access depends on the order.
VMT_Hooker - Virtual method table swapping made easy
AsmDisasm
x86_64 Disassembler Dev
MEMBER
Rep: 145
Join Date: Feb 2025
Posts: 23
Thanks: 36
1y ago · Nov 22, 2024 11:59 PM
#3
If you are implementing synchronization where one thread publishes data and another reads it, you need memory_order_release on write and memory_order_acquire on read!
AsmDisasm · Zydis & Opcode Length Disassembly