简体   繁体   English

对原子变量的非原子操作

[英]Non atomic operation on atomic variables

Suppose I have this code:假设我有这个代码:

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);

Can I replace that with the following to avoid two atomic reads (is it safe?):我可以用以下内容替换它以避免两次原子读取(安全吗?):

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);

Also can I use something like this code to write an atomic variable without it being an atomic write?我也可以使用类似这样的代码来编写原子变量而不是原子写入吗?

*reinterpret_cast<int*>(&a2) = 5;

Nope, you can't.不,你不能。

If you have a platform where reads of aligned integers are always atomic, then you haven't avoided any atomic operations.如果您有一个平台,其中对齐整数的读取始终是原子的,那么您就没有避免任何原子操作。 If you have a platform where reads of aligned integers aren't always atomic, then the code is obviously unsafe.如果您有一个平台,其中对齐整数的读取并不总是原子的,那么代码显然是不安全的。

It would be great to be able to use atomic and non atomic types interchangeably when atomicity is or isn't needed.当需要或不需要原子性时,能够互换使用原子和非原子类型会很棒。 However nothing in the C++ model allow it and lots of things go against it.然而,C++ 模型中没有任何东西允许它,而且很多事情都与它背道而驰。

But the memory model is unsound in the first place (as in: it doesn't define the behavior of anything, it's senseless) so it should be rebuild from scratch and then what you propose should be considered.但是内存模型首先是不健全的(例如:它没有定义任何行为,它毫无意义)所以它应该从头开始重建,然后你应该考虑你的建议。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM