我想比较和交换 3 个原子变量:
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);
但是,如果在读取expected
和new
变量之间并将它们与 进行比较a
,另一个线程更改它们的值,当前线程将按以前的值工作,所以我将代码更改为它:
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;
}
我的代码正确吗?还是有更好的方法来做到这一点?