2

我对volatile用法有疑问。我通常尝试跨线程共享的所有变量都具有volatile确保直接内存访问的关键字,当然还使用互斥锁进行保护。

但是,volatile如果共享变量以确保一致性,是否真的需要?

我用一个例子来解释:

Thread1: //(affects it behaviour with the variable)
mymutex.lock();
if(variable)
{
   ...
   variable = false;
}
mymutex.unlock();

Thread2:
mymutex.lock();
variable = true;
mymutex.unlock();

在上面的示例中,thread2仅写入和thread1读取/写入。是否有可能variable被缓存并且线程不读取新值?即使互斥锁设置正确?volatile在这种情况下我需要吗?

我问这个是因为我有一个变量而不是变量std::vector,它不能是易变的。而且我不是 100% 确定这种方法在没有volatile关键字的情况下是安全的。

谢谢。

编辑:正确地重新提出问题。

4

2 回答 2

5

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.

于 2013-10-30T14:27:33.373 回答
0

看看我的回答here

底部喜欢,不要聪明是使用 volatile 来尝试保证线程安全,使用正确

于 2013-10-30T14:51:41.370 回答