avatar
C++ volatile请教# JobHunting - 待字闺中
b*e
1
volatile告诉编译器不要做优化,读和写直接到memory,一些情况下我知道要用
volatile:
int flag = 1;
while(flag == 1)
{
}
如果其他线程可能会改变flag,这里需要是volatile,否则编译器会优化为 while(
true)
但是如果在多线程下一个变量已经被用synchronisation primitive保护了:
lock(mutex)
int tt = 5;
unlock(mutex)
我们还需要把它申明为volatile吗?否则的话,一个线程改变了变量的值,还没有写到
memory,但释放了metex,另一个线程获得metex,access变量,但memory中的变量的值
还是旧的没改变的。简短来说,就是已经被critical section或metex保护的变量在多
线程中还有必要申明为volatile吗?
avatar
h*e
2
这好象不是volatile的原本用法。它的原本用法是:一些外部进程
会改变该变量的值,要求编译器产生代码的时候不能放在寄存器里,
每次都要重新读一遍,例如当一段IO地址map到一段内存时。

【在 b********e 的大作中提到】
: volatile告诉编译器不要做优化,读和写直接到memory,一些情况下我知道要用
: volatile:
: int flag = 1;
: while(flag == 1)
: {
: }
: 如果其他线程可能会改变flag,这里需要是volatile,否则编译器会优化为 while(
: true)
: 但是如果在多线程下一个变量已经被用synchronisation primitive保护了:
: lock(mutex)

avatar
y*u
3
你错了,他是对的
不是不能放在寄存器里,是不能优化。。。

【在 h****e 的大作中提到】
: 这好象不是volatile的原本用法。它的原本用法是:一些外部进程
: 会改变该变量的值,要求编译器产生代码的时候不能放在寄存器里,
: 每次都要重新读一遍,例如当一段IO地址map到一段内存时。

avatar
h*e
4
我觉得不能优化就包括不存在寄存器里:
"If you use the volatile modifier on a variable, the compiler
won't cache that variable in registers — each access will hit
the actual memory location of that variable. "
http://www.drdobbs.com/cpp/184403766
回到LZ最初问的问题,“是不是被Mutex之类的保护的变量是不是就不需要
声明volatile了”,我觉得应该是不需要了吧。同样一篇文章说道:
Inside a critical section defined by a mutex, only one thread has
access. Consequently, inside a critical section, the executing code
has single-threaded semantics. The controlled variable is not volatile
anymore — you can remove the volatile qualifier.
相关阅读
logo
联系我们隐私协议©2024 redian.news
Redian新闻
Redian.news刊载任何文章,不代表同意其说法或描述,仅为提供更多信息,也不构成任何建议。文章信息的合法性及真实性由其作者负责,与Redian.news及其运营公司无关。欢迎投稿,如发现稿件侵权,或作者不愿在本网发表文章,请版权拥有者通知本网处理。