This has been bothering me for a while, but to take a recent example, a question like What are the optimal std::memory_orders for this scenario of a coroutine waiting on an event? is about what std::memory_order
should be used with the atomic load, store, and RMW operations. But despite this, the question got posted with the memory-barriers tag because memory-order is currently a synonym for memory-barriers.
It doesn't involve std::atomic_thread_fence
, and if compiled for AArch64, won't need any barrier instructions instructions like dmb ish
, just ordered loads and stores with std::memory_order_acquire
and std::memory_order_release
ordering. Even std::memory_order_seq_cst
doesn't need separate barriers on AArch64, as ldar
loads can't reorder with later stlr
stores. Similarly for x86, if the pure loads and stores can all be weakened to acquire
and release
, so at most the RMWs are still seq_cst
, then no separate barrier instructions are needed to implement the C++. (x86 does need a barrier to do a seq_cst store, or do them with xchg
instead of mov+mfence).
And more importantly, whether a compiler needs to use any barrier instructions to implement the C++ semantics in the asm is just an implementation detail, quite separate from the correctness of the memory-order specified for operations. foo.load(std::memory_order_acquire)
is not a memory barrier, it just has one-way ordering. If fences like std::atomic_thread_fence(acquire)
were that weak, they wouldn't work. (Which is why they are in fact 2-way barriers).
When reasoning about correctness with different memory orders on your atomic operations in portable C++, you should be thinking in terms of operations, not in terms of how they compile to 2-way barriers on some ISAs like PowerPC or ARM before ARMv8. (Or if the argument is that "barrier" can describe the 1-way ordering of an atomic operation, then I don't like that confusing naming.)
So perhaps we should un-synonymize (https://stackoverflow.com/tags/memory-barriers/synonyms) memory-order and memory-ordering from memory-barriers + memory-fences.
Or better, reverse things so memory-order is the primary tag, i.e. make memory-barriers and memory-fences synonyms of memory-order.
Most of the time when I find myself adding one of those tags to a post, or see a new post with that tag, the right name is memory-order.
Using memory barriers/fences is one way to achieve ordering, so memory-order is the more general concept we're collecting together, currently under the memory-barriers tag name. I think the best end result would be to have all 4 of those tags still be synonyms, but of memory-order. (If that's easily possible.)
In case anyone's looking at similarly named tags, barrier is about a separate concept: a thread-synchronization building block where threads that call barrier(foo)
sleep until all threads have called barrier(foo)
, then they all wake up. This is unrelated to memory ordering and fences.