I don't completely understand why atomic wait needs a memory order parameter. It compares its own value, so the atomic value itself is synchronized anyway. I couldn't figure out an example where anything else than std::memory_order_relaxed
makes sense.
If I need additional logic based on the atomic variable I need to call other functions (with separate memory order specification) anyway, as wait is void, e.g.:
void waitToBeEmpty() noexcept
{
ssize_t currSize{ m_queueSize.load(std::memory_order_acquire) };
while (currSize > 0) {
m_queueSize.wait(currSize, std::memory_order_relaxed);
currSize = m_queueSize.load(std::memory_order_acquire);
}
}
Why do we need to specify a memory order for atomic wait?
CodePudding user response:
If I need additional logic based on the atomic variable I need to call other functions
Do you?
Consider if T
is a bool
. It only has one of two states: true
or false
. If you wait
until it is not true
, then it must be false
and no further atomic operations are needed.
And that's just the case where T
is a type that can only (generally) assume two values. There are also cases where T
is a type that technically can assume more values, but you're only using two of them. Or the cases where T
could have multiple values, but your waiting code doesn't care which one it is, merely that it isn't the one you asked to wait on. "Is not zero" is a common example, as you may not care which kind of "not zero" it is.