The usefulness of volatiles in parallel programming with C ++ 11

I read this and this answer. I also searched the C ++ Concurrency book in action and did not find a discussion about volatile, nor did I use it. It doesn't seem to be designed for concurrency at all. So, for parallel programming is it simple enough to use atomic, mutex, etc. And forget about volatile? Any cases where you volatilemight need for concurrency problems?

+4
source share
2 answers

No, in C ++ the keyword volatiletells the compiler that it should not optimize the variable in any form or form. This can be useful when working with memory that can be changed outside of your own code, for example, on a hardware registry on a user board.
For a more detailed guide to volatile, you should read Volatile vs. volatile Herb Sutter

+7
source

volatileand atomic- two orthogonal concepts. Therefore, their combination changes the program semantics, otherwise they will not be orthogonal!

atomicity causes restrictions on the sequence (including atomicity of reading and writing).

volatility causes restrictions on access to a variable.

volatile , - . , , , :

//thread A
extern std::atomic<int> progress;
//
void compute(){
  progress=0;
  //do something;
  progress=1;
  //do something;
  progress=2;
  //[...] a 100 time.
  }

, progress , . :

void compute(){
  //do many thing;
  progress=100;
  }

volatile atomic<int> progress;, , , .

. :

+2

Source: https://habr.com/ru/post/1693802/


All Articles