多线程应用程序上的易失性C / C ++ [英] Volatile C/C++ on a multithread app

查看:187
本文介绍了多线程应用程序上的易失性C / C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



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



我用一个例子解释:

  Thread1://(影响它与变量的行为)
mymutex.lock();
if(variable)
{
...
variable = false;
}
mymutex.unlock();






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

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



我问这是因为我有一个 std :: vector ,这不能是volatile。我不是100%肯定这种方法是安全的没有 volatile 关键字。



谢谢。 >

EDITED:正确重构问题。

解决方案

C ++中的易失性不是用于并发。它是关于编译器是否允许优化从一个变量读取或不。不幸的是,这意味着,即使你有 volatile ,它也可以通过内存映射与硬件连接。



c $ c>变量,读和写可能仍然访问不同步的线程本地存储。此外, std :: vector 不是线程安全的。



,例如使用 std :: mutex (你提到)。现在,如果这样做,由 mutex 保护的变量不需要 volatile mutex 本身执行同步,并防止您担心的类型的问题。


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.

解决方案

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.

这篇关于多线程应用程序上的易失性C / C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆