'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. It does this by removing machine caches of certain variables and disabling CPU instruction reordering under some cases at each write.

I noted that volatile exists in C++, while it serves different purposes. I wonder how C++ implements cache coherence and other things that goes with volatile in Java.



Solution 1:[1]

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. Java's volatile semantics are one of those, as was the ability to synchronize on every object.

C++ does not implement cache coherence. That's something for compilers and CPU's. At the C++ level, you have ordered operations. A happens-before B. One such case, that could be compared with volatile in some sense, are C++ atomics.

Solution 2:[2]

Modern mainstream CPUs have coherent caches. That is taken care of by the cache coherence protocol. This is independent if a field is (Java) volatile or not. 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).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 MSalters
Solution 2