To Volatile, or not to Volatile?
Hello everybody,
I'm a bit confused by the keyword "volatile". My biggest issue is: everybody seems to be saying different things.
I've written a class, with two threads, one thread going into an loop as long as a certain flag in the class is true. The regular thread sets this flag in the constructor and destructor of the class.
The pseudo-code:
Code:
class SomeClass {
public:
SomeClass()
: isRunning_(true)
{
createThread();
}
~SomeClass()
{
isRunning_ = false;
waitForThread();
}
protected:
void threadFunction()
{
while(isRunning_) {
...
}
}
...
private:
[volatile??] bool isRunning_;
};
Now my question is: does isRunning_ need to be volatile? If not, I could imagine the compiler optimizing the "while(isRunning_)" bit to "if(isRunning_) while(true)", so I would say I need it. However, many sources on the internet say volatile is useless in any case for threading (and no, they're not just talking about making a technique to implement critical sections).
So should I use volatile here? And why, or why not?
Thanks in advance,
Evoex