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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

GhostHunter_x
Unity & Phasmo Modder
VIP
Rep: 275
Join Date: Apr 2023
Posts: 17
Thanks: 71
4y ago · Aug 22, 2021 7:15 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?
GhostHunter_x · Phasmophobia & Unity Reverser
GhostAI, Sanity, EMF & Evidence inspection
The following users thanked GhostHunter_x for this post:
IL2Cpp_Wizard
IL2Cpp & Metadata Engineer
VIP
Rep: 360
Join Date: Feb 2023
Posts: 21
Thanks: 92
4y ago · Aug 22, 2021 9:58 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.
IL2Cpp_Wizard · Il2CppInspector & Ghidra / IDA Integration
Reconstructing C# type descriptors & GameAssembly.dll offsets
AsyncMaster
Concurrency Geek
MEMBER
Rep: 72
Join Date: Jul 2020
Posts: 13
Thanks: 83
4y ago · Aug 22, 2021 11:58 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!
AsyncMaster · Concurrency Geek
Task Parallel Library (TPL), async/await internals, and lock...