I want to compare and exchange 3 atomic variable:
std::atomic<int> a;
std::atomic<int> expected;
std::atomic<int> new;
int expectedValue = std::atomic_load_explicit(&expected, std::memory_order_relaxed);
int newValue = std::atomic_load_explicit(&new, std::memory_order_relaxed);
std::atomic_compare_exchange_strong_explicit(
&a,
&expectedValue,
newValue,
std::memory_order_relaxed,
std::memory_order_relaxed);
But if in between reading expected
and new
variables and comparing them to a
, one another thread change theirs values, current thread will work by previous values, so i change code to it:
while(true)
{
int expectedValue = std::atomic_load_explicit(&expected, std::memory_order_relaxed);
int newValue = std::atomic_load_explicit(&new, std::memory_order_relaxed);
std::atomic_compare_exchange_strong_explicit(
&a,
&expectedValue,
newValue,
std::memory_order_relaxed,
std::memory_order_relaxed);
int newExpectedValue = std::atomic_load_explicit(&expected, std::memory_order_relaxed);
int newNewValue = std::atomic_load_explicit(&new, std::memory_order_relaxed);
if(newExpectedValue == expectedValue && newNewValue == newValue)
break;
}
Is my code correct? or is there a better way to do this?