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

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Question

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

ImGuiCustomizer
Custom Controls
MEMBER
Rep: 96
Join Date: Mar 2022
Posts: 6
Thanks: 95
5y ago · Feb 4, 2021 4:57 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?
ImGuiCustomizer · Custom Controls
Creating tabs, toggle switches, and responsive layouts in De...
The following users thanked ImGuiCustomizer for this post:
RenderLoop
Graphics Pipeline Dev
MEMBER
Rep: 348
Join Date: Jul 2020
Posts: 6
Thanks: 94
5y ago · Feb 4, 2021 9:17 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.
RenderLoop · Graphics Pipeline Dev
Double buffering, triple buffering, vertical sync, and frame...
CodeRefactorer
Software Architect
MEMBER
Rep: 296
Join Date: Feb 2021
Posts: 6
Thanks: 21
5y ago · Feb 6, 2021 1:17 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!
CodeRefactorer · Software Architect
Clean architecture, SOLID principles, and refactoring legacy...