假设我有这个代码:
std::atomic<int> a1;
std::atomic<int> a2;
std::atomic<int> a3;
std::atomic_store(&a1, 1);
std::atomic_store(&a2, 1);
std::atomic_store(&a3, 2);
int a2Value = std::atomic_load_explicit(&a2, std::memory_order_relaxed);
int a3Value = std::atomic_load_explicit(&a3, std::memory_order_relaxed);
std::atomic_compare_exchange_strong_explicit(
&a1,
&a2Value,
a3Value,
std::memory_order_relaxed,
std::memory_order_relaxed);
我可以用以下内容替换它以避免两次原子读取(安全吗?):
a2Value = static_cast<int>(a2);
a3Value = static_cast<int>(a3);
std::atomic_compare_exchange_strong_explicit(
&a1,
&a2Value,
a3Value,
std::memory_order_relaxed,
std::memory_order_relaxed);
我也可以使用类似这样的代码来编写原子变量而不是原子写入吗?
*reinterpret_cast<int*>(&a2) = 5;