There are already a few questions on Stackoverflow that essentially ask about the use cases of memory_order_relaxed
, such as:
Understanding memory_order_relaxed
What are some use cases for memory_order_relaxed
However, I'm still confused about the precise semantics of memory_order_relaxed
. Generally, the example use case for memory_order_relaxed
is something like std::shared_ptr
- basically it keeps an atomic counter, but it doesn't need to sync with other threads.
Okay, so my understanding is as follows:
std::memory_order_relaxed
, when used with load()
only guarantees that the thread which loads it will do so atomically - it makes no guarantee about any orderings with respect to other threads that do store()
operations on the same variable, and it makes absolutely no guarantee about any loads/stores of non-atomic variables (i.e. no memory fence will be generated.)
But does memory_order_relaxed
provide ANY sort of "happens-before" type ordering ability, with regard only to the single atomic value? For example, if we have:
std::atomic_flag x = ATOMIC_FLAG_INIT;
// Thread A:
//
if (!x.test_and_set(std::memory_order_relaxed)) {
std::cout << "Thread A got here first!" << std::endl;
}
// Thread B:
//
if (!x.test_and_set(std::memory_order_relaxed)) {
std::cout << "Thread B got here first!" << std::endl;
}
In the above example, even though we used memory_order_relaxed
, haven't we also provided a guaranteed way to reason about ordering here? In other words, both Thread A and Thread B will be able to reason about which thread set the flag first. It's just that, due to the relaxed ordering, neither thread A nor thread B will be able to assume anything about the values of any surrounding non-atomic shared variables, since there is no memory fence. Or am I incorrect here?
You're correct. And as you noted, there are use cases (such as a counter) where that's fine.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With