问题
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.
回答1:
volatile in C++ is not meant for concurrency. It's about whether the compiler is allowed to optimize away reads from a variable or not. It is primarily used for things such as interfacing with hardware via memory mapping.
Unfortunately, this means that even if you do have volatile variables, the reads and writes may still access a thread-local store which is not synchronized. Also, an std::vector is not thread safe.
So, in either case, you need to synchronize, for example using a std::mutex (which you do mention). Now, if this is done, the variables which are protected by that mutexdo not need to be volatile. The mutex itself does the synchronization and protects against the type of issues you worry about.
回答2:
Take a look at my answer here.
Bottom like, don't be clever are use volatile to try guarantee thread safety, use proper
来源:https://stackoverflow.com/questions/19684781/volatile-c-c-on-a-multithread-app