Unprotected get function in a multi-threaded system - requires volatility?

I am working on a multi-threaded program that provides access to one side of an interprocess communication system. Having never used volatility, I am trying to figure out its proper use.
I understand that (the corresponding part) volatile tells the compiler that the variable to which it is applicable can be written out of the sequence of instructions of this stream, so it must reread the memory every time it is used.

I looked at some tutorials on volatile, but most of them either have the simplest examples (like a global shared variable), or just copy each other. Then from time to time, I see that someone believes that volatility does not do what you think. In addition, some people say that if you are not writing device drivers or some, you should not use volatile ( Is 'volatile' necessary for this multi-threaded C ++ code? ). At the moment, I have a brain in the node, and I don’t even know if the things I'm worried about are real problems. So I'm wondering if there is any example of volatile usage code in OOP that I could look at.

But, in particular, my main problem is related to the external use of the getter function. In my code, everything that I use is correctly protected, however, I provide some getter functions for private member variables that I do not protect (similar to this question, Overhead of pthread? Mutexes , especially the last paragraph of the first answer, or unprotected access to to the member in the get property ) because I don’t want to bind my record thread, especially if several wait loops are waiting in loops using the get function.

I worry that if I do not set the variable that I access the get function as volatile, then if some external program waits on it in a loop, then the compiler for this external program may not re-read the variable, so the external program will remain in infinite loop. Is this a serious problem?

A very similar question here , but I'm not sure if the answer was for C ++.

+4
source share
2 answers

The "Some People" you are talking about are completely true. Using volatile ensures that memory is read or written every time you do this in code. It does not guarantee that this value is current or noticed by other threads that can run on a separate core or separate CPU. For this you need a memory barrier.

When using a device to read or write external equipment in the driver, this is not a problem, since the hardware will be mapped to non-cached memory.

+3
source

In C ++, volatile not used for multithreading (at least not as it was assumed in Java 5, which provides a memory barrier or the like). C ++ 0x has atomic variables, and this is closest to Java 5-style volatile .

+3
source

All Articles