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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

ParanormalDev
MelonLoader / BepInEx Dev
MEMBER
Rep: 230
Join Date: Sep 2023
Posts: 21
Thanks: 58
5y ago · Aug 13, 2021 1:39 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?
ParanormalDev | MelonLoader & ImGui Modding
The following users thanked ParanormalDev for this post:
CSharpNinja
Senior .NET Developer
VIP
Rep: 329
Join Date: Jan 2020
Posts: 16
Thanks: 75
5y ago · Aug 13, 2021 6:05 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.
CSharpNinja · Senior .NET Developer
C# enthusiast, building distributed backend services and hig...
ImGuiFanatic
Graphics & ImGui
MEMBER
Rep: 159
Join Date: Aug 2021
Posts: 6
Thanks: 35
5y ago · Aug 14, 2021 7:05 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!
ImGuiFanatic · Graphics & ImGui
Dear ImGui is the best GUI library ever made. Change my mind...