Home / Forums / How does std::atomic memory_order_relaxed differ from memory_order_seq_cst?

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

How does std::atomic memory_order_relaxed differ from memory_order_seq_cst?

ApexPredator_
Source Engine Modder
VIP
Rep: 340
Join Date: May 2022
Posts: 23
Thanks: 88
1y ago · Nov 4, 2024 6:30 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?
ApexPredator_ · Source Engine Specialist
The following users thanked ApexPredator_ for this post:
GlowShader
Shader & Overlay Artist
MEMBER
Rep: 185
Join Date: Oct 2023
Posts: 36
Thanks: 46
1y ago · Nov 4, 2024 9:02 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.
GlowShader | Shaders, Stencils & DirectX DrawLists
CitizenNative
RAGE Engine & FiveM Dev
VIP
Rep: 315
Join Date: Sep 2022
Posts: 21
Thanks: 82
1y ago · Nov 6, 2024 2:02 AM
#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!
CitizenNative | RAGE Engine & FiveM Native Calls