简体   繁体   English

C++ 中 Java volatile 的作用是什么?

[英]What serves the same purpose of Java volatile in C++?

I learned the volatile keyword in Java. It serves as a mean to ensure visibility in other threads when a variable is written by one particular thread.我在 Java 中学习了volatile关键字。当变量由一个特定线程写入时,它用作确保其他线程可见性的一种手段。 It does this by removing machine caches of certain variables and disabling CPU instruction reordering under some cases at each write.它通过删除某些变量的机器缓存并在某些情况下在每次写入时禁用 CPU 指令重新排序来实现这一点。

I noted that volatile exists in C++, while it serves different purposes.我注意到volatile存在于 C++ 中,但它有不同的用途。 I wonder how C++ implements cache coherence and other things that goes with volatile in Java.我想知道 C++ 如何实现缓存一致性以及 Java 中与volatile相关的其他内容。

Modern mainstream CPUs have coherent caches.现代主流 CPU 具有一致的缓存。 That is taken care of by the cache coherence protocol.这由缓存一致性协议负责。 This is independent if a field is (Java) volatile or not.如果字段是 (Java) 易失性的,这是独立的。 So there is also coherence on plain loads/stores.因此,普通加载/存储也具有一致性。 Although it can be that higher up the chain coherence is violated.尽管更高的链条连贯性可能会被破坏。

The C++ version of Java volatile would be an atomic with memory_order_seq_cst (which is the default). Java volatile 的 C++ 版本将是具有 memory_order_seq_cst(默认)的原子。

There is no replacement.没有替代品。

C++11 derives its memory model from Java, but it explicitly acknowledged that some Java choices turned out to be suboptimal. C++11 从 Java 派生出它的 memory model,但它明确承认一些 Java 的选择被证明是次优的。 Java's volatile semantics are one of those, as was the ability to synchronize on every object. Java 的volatile语义就是其中之一,在每个 object 上同步的能力也是如此。

C++ does not implement cache coherence. C++没有实现缓存一致性。 That's something for compilers and CPU's.这是编译器和 CPU 的事情。 At the C++ level, you have ordered operations. C++ 层,您有订单操作。 A happens-before B. One such case, that could be compared with volatile in some sense, are C++ atomics. A happens-before B。在某种意义上可以与volatile进行比较的一个这样的情况是 C++ 原子。

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

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