Developer knowledge network · moderated exchange

Супольнасць UnreliableCode

Супольнасць распрацоўшчыкаў даследаванняў, зваротнага праектавання і кадавання

Knowledge indexжыць
4Categories
919Threads
2.8KПаведамленні
Discussion

Comparing std::atomic<T> memory models: Sequentially Consistent vs Relaxed Performance [StackOverflow Architecture Guide]

cpp_concurrency_guru
C++ Standards Expert
MEMBER
прадстаўнік: 47
Дата далучэння: Feb 2018
Паведамленні: 17
Дзякуй: 75
1 месяцаў таму · Jul 6, 2026 9:46 PM
#1

When is std::memory_order_relaxed actually safe to use?

Relaxed atomic operations guarantee atomicity (no data races on the single variable itself) but provide zero synchronization or ordering constraints relative to other memory accesses.

CPP
// Safe for independent counters
std::atomic<uint64_t> g_totalPacketCount{0};
void OnPacketReceived() {
    g_totalPacketCount.fetch_add(1, std::memory_order_relaxed);
}

Because other threads only read the counter for telemetry (without relying on it to guard other data), relaxed is 100% safe and saves CPU pipeline synchronization cycles on ARM and RISC-V.

memory_model_mook
Low-Level C Veteran
MEMBER
прадстаўнік: 163
Дата далучэння: Jan 2019
Паведамленні: 11
Дзякуй: 33
1 месяцаў таму · Jul 7, 2026 1:46 AM
#2

Use relaxed for metrics, telemetry, and statistics. Use acquire-release for flags that synchronize shared buffers.

profiler_pat
Performance Hunter
MEMBER
прадстаўнік: 146
Дата далучэння: Aug 2019
Паведамленні: 33
Дзякуй: 31
1 месяцаў таму · Jul 7, 2026 8:31 PM
#3

Clear rule of thumb that prevents over-synchronization in high-throughput engines.