I am having a question on the volatile
usage. I typically try that all the variables shared across threads have the volatile
keyword to ensure direct memory accesses, and of course protected with mutexes.
However, is volatile
really needed if a variable is shared to ensure consistency?
I explain with an example:
Thread1: //(affects it behaviour with the variable)
mymutex.lock();
if(variable)
{
...
variable = false;
}
mymutex.unlock();
Thread2:
mymutex.lock();
variable = true;
mymutex.unlock();
In the upper example, thread2
only writes, and thread1
reads/writes. Is it possible that the variable
is cached and the threads do not read the new value? Even though the mutexes are properly set? Do I need volatile
in this case?
I am asking this because instead of variable I have a std::vector
, which cannot be volatile. And I am not 100% sure that this approach is safe without the volatile
keyword.
Thanks.
EDITED: Reformulating the question properly.