java 和 C++11 易失性
我想将一些代码从 Java 移植到 C++11,但我对 volatile 关键字有点困惑。
我对Java语言不熟悉,也不明白什么是易失性变量。它保证每个线程都可以访问变量的最新值 - 这是 C++ 易失性行为。但它通常用于同步——对易失性变量执行的所有操作都是原子的吗?
所以我认为 C++11 很好的替代 Java 易失性的是 std::atomic。或者我完全错了,因为我错过了一些额外的 Java 易失性功能?
I'd like to port some piece of code from Java to C++11 and I'm a bit confused with volatile keyword.
I'm not familiar with Java language and I don't get what a volatile variable is. It guarantees that every thread has access to the up to date value of variable - it is the C++ volatile behaviour. But it is usually used to synchronize - are all actions performed on volatile variable atomic?
So I think thath the C++11 good replacement for Java volatile will be std::atomic. Or I'm totally wrong, cause I missed some additional Java volatile features?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,他们会是一个很好的匹配,Dr Dobbs 有一篇关于此的好文章。
Java 将这种类型的变量提供为
volatile
,C++ 将其提供为std::atomic
。Yes, they would be a good match, there is a good article on this at Dr Dobbs.
Java provides this type of variable as
volatile
, C++ asstd::atomic
.此页面对 Java 的
volatile
关键字有一个非常好的解释:http:// www.javamex.com/tutorials/synchronization_volatile.shtml。在我看来,基本类型(例如整数)上的 C++11 std::atomic 确实是一个很好的替代品。请注意,std::atomic
提供对读取-修改-写入操作的支持(例如,compare_exchange_strong
和fetch_add
)。This page has a pretty nice explanation on Java's
volatile
keyword: http://www.javamex.com/tutorials/synchronization_volatile.shtml. It looks to me that C++11std::atomic<>
on primitive types (e.g., integers) indeed is a good replacement. Note thatstd::atomic<>
provides support for read-modify-write operations (e.g.,compare_exchange_strong
andfetch_add
).