Reputation: 14967
I've read this and this answer. I've also searched the book C++ Concurrency in Action and found no discussion about volatile
nor any example using it. Looks like it's not designed for concurrency at all. So for concurrent programming, is it sufficient to just use atomic, mutex, etc., and forget about volatile
? Any cases where volatile
may be needed for concurrency issues?
Upvotes: 5
Views: 366
Reputation: 18041
volatile
and atomic
are two orthogonal concepts. So their combination change the program semantic, otherwise they would not be orthogonal!
atomicity causes constraints on sequencing ( included atomicity of read and write).
volatility causes constraints on the elidability of accesses to the variable.
volatile
does not cause any sequencing between thread, nevertheless it is still usefull. Consider this program, that show a progress bar, the computation is performed in one thread, while another thread is responsible for the graphics:
//thread A
extern std::atomic<int> progress;
//
void compute(){
progress=0;
//do something;
progress=1;
//do something;
progress=2;
//[...] a 100 time.
}
Inside the function compute, the compiler notice that progress
is never read but just written many time. So it can optimize the code to:
void compute(){
//do many thing;
progress=100;
}
By declaring volatile atomic<int> progress;
all the writes will not be collapsed, and the memory order will ensure that operations will be performed inbetween of all these writes.
See also:
P0063R1: When Should Compiler Optimize Atomics, where my example comes from.
Upvotes: 3
Reputation: 196
No, in C++ the volatile
keyword tells the compiler that must not optimize the variable in any way shape or form. This can be useful when dealing with memory that can be changed from outside of your own code e.g a hardware register on a custom board.
For more in depth guide about volatile you should read Volatile vs. volatile
By Herb Sutter
Upvotes: 7