Skip to content
TopicTracker
From HackerNewsView original
TranslationTranslation

C++ Details of Asymmetric Fences

The article explores asymmetric memory fence patterns in C++, focusing on how store-load ordering can be optimized using techniques like membarrier() on Linux. It details the trade-offs between full barriers and lighter-weight alternatives, demonstrating scenarios where asymmetric fences improve performance while maintaining correctness in lock-free programming.

Background

- The article discusses **asymmetric fences** in C++ — a low-level memory-ordering technique where one thread uses a heavyweight fence (e.g., `std::atomic_thread_fence(std::memory_order_seq_cst)`) while another uses only a lightweight compiler barrier (`asm volatile("" ::: "memory")`). This asymmetry can be correct on certain CPU architectures (x86, ARMv8) and is exploited in high-performance code like Linux's `membarrier()` syscall and user-space RCU (Read-Copy-Update). - **membarrier()** is a Linux syscall that lets a thread issue memory barriers on behalf of other threads in the same process, enabling fast paths that avoid barriers entirely in hot code. - The post assumes familiarity with C++ memory ordering (`memory_order_acquire`, `release`, `seq_cst`), compiler barriers vs. CPU fences, and the difference between "strongly ordered" architectures like x86 (where most loads/stores are already ordered) and "weakly ordered" ones like ARM/PowerPC. - Key takeaway: what looks like a bug in the C++ abstract machine can be correct on real hardware when you know the microarchitecture — but the C++ standard alone cannot guarantee correctness across all platforms.

Related stories