
Originally Posted by
phantomotap
You say you are protecting reads and writes to `isRunning_' (Curse you for making me type '_' at the end!) with a "mutex". If that "mutex" is a full mutually exclusive lock the variable `isRunning_' does not need to be `volatile' in the context you've used it in the original post. The lock protects writes from the great "elsewhere" while reading so can't be updated beyond that scope so the cached value may be safely assumed to be correct.
I guess I didn't understand volatile as well as I thought, then (sorry for my confusion). The code more accurately looks like this (should've written this in the first place):
Code:
class SomeClass {
public:
SomeClass()
: isRunning(true)
{
createThread();
}
~SomeClass()
{
pthread_mutex_lock(...);
isRunning = false;
pthread_mutex_unlock(...);
waitForThread();
}
protected:
void threadFunction()
{
while(1) {
pthread_mutex_lock(...);
if(!isRunning)
break;
pthread_mutex_unlock(...);
...
}
}
...
private:
[volatile??] bool isRunning;
};
(I know, I'm not unlocking the mutex, again, laziness, but I did remove the underscore for you ;-).
However, I don't see how that would make a difference. As I understood it, the compiler could still recognize that the isRunning variable is not modified in the function and thus must always remain the same, allowing it to cache the value, or store it in a register, rather than reading it from memory every time it's accessed.
So what's the error in my logic, or my understanding of volatile?
Thanks!
Evoex