为什么在 std::atomic 中使用 volatile 限定符?
从我读到的 Herb Sutter 和 其他人你可能会认为易失性
和并发编程是完全正交的概念,至少就C/C++而言是这样。
但是,在 GCC 实现 中,所有 std:: atomic
的成员函数具有 volatile
限定符。 Anthony Williams 的 std 实现 也是如此::原子
。
那么,这是怎么回事,我的 atomic
变量是否需要是 volatile
?
From what I've read from Herb Sutter and others you would think that volatile
and concurrent programming were completely orthogonal concepts, at least as far as C/C++ are concerned.
However, in GCC implementation all of std::atomic
's member functions have the volatile
qualifier. The same is true in Anthony Williams's implementation of std::atomic
.
So what's deal, do my atomic<>
variables need be volatile
or not?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
总结一下其他人正确编写的内容:
C/C++
易失性
用于硬件访问和中断。 C++11atomic
用于线程间通信(例如,在无锁代码中)。这两个概念/用途是正交的,但它们具有重叠的要求,这就是人们经常混淆两者的原因。atomic
具有 volatile 限定函数的原因与它具有 const 限定函数的原因相同,因为原则上一个对象可以同时是atomic
> 以及const
和/或易失性
。当然,正如我的文章所指出的,另一个令人困惑的来源是 C/C++
易失性
与 C#/Java易失性
不同(后者基本上是等价的)到 C++11atomic
)。To summarize what others have correctly written:
C/C++
volatile
is for hardware access and interrupts. C++11atomic<>
is for inter-thread communication (e.g., in lock-free code). Those two concepts/uses are orthogonal, but they have overlapping requirements and that is why people have often confused the two.The reason that
atomic<>
has volatile-qualified functions is the same reason it has const-qualified functions, because it's possible in principle for an object be bothatomic<>
and alsoconst
and/orvolatile
.Of course, as my article pointed out, a further source of confusion is that C/C++
volatile
isn't the same as C#/Javavolatile
(the latter is basically equivalent to C++11atomic<>
).为什么在整个
std::atomic
中使用易失性
限定符?因此易失性对象也可以是原子的。请参阅此处:
相关报价是
我的
原子
变量是否需要易失性
?不,原子对象没有不稳定。
Why is the
volatile
qualifier used throughoutstd::atomic
?So that volatile objects can also be atomic. See here:
The relevant quote is
Do my
atomic<>
variables need to bevolatile
or not?No, atomic objects don't have to be volatile.
与 const 一样,易失性是传递性的。如果将方法声明为
易失性
,则无法对其或其任何成员属性调用任何非易失性方法。通过使用std::atomic
方法易失性
,您允许从包含std::atomic
的类中的易失性
成员方法进行调用代码>变量。我今天过得不太好……太令人困惑了……也许一个小例子有帮助:
As const, volatile is transitive. If you declare a method as
volatile
then you cannot call any non-volatile method on it or any of its member attributes. By havingstd::atomic
methodsvolatile
you allow calls fromvolatile
member methods in classes that contain thestd::atomic
variables.I am not having a good day... so confusing... maybe a little example helps: