【发布时间】:2016-12-03 09:45:09
【问题描述】:
volatile 关键字是否强制跨线程可见性?例如:
volatile int bar;
mutex mut;
void foo()
{
bar = 4;
// (*) Possible other thread changes to `bar`. No instructions here,
// just time that passes.
lock(&mut);
// (1) If 'bar' had _not_ been declared 'volatile', would the compiler
// be allowed to assume 'bar' is '4' here?
//
// (2) If 'bar' _is_ declared 'volatile', the compiler is
// forced to add the necessary instructions such that changes to
// 'bar' that may have occurred during (*) are visible here.
unlock(&mut)
}
不询问原子性或顺序(我假设lock(mutex) 的任何合理实现都会在适合架构的情况下添加适当的内存和编译器围栏)- 只是可见性问题。
【问题讨论】:
-
什么叫“可见性”?如果您的意思是“所有线程都可以读取或写入变量”,编译器会告诉您。如果您的意思是“线程将看到分配的最后一个值”,那么问题确实与原子性或排序有关。请澄清。
-
@YvesDaoust 我的意思是“线程将看到分配的最后一个值”,但是,假设编译器/内存栅栏插入在
lock/unlock周围,不要认为原子性或排序会出现在这里发挥作用。 -
抱歉,这是正是关于原子性或排序。在分配和锁定之间可能发生任何事情,无论是否易失。作业可能应该在关键部分内。
-
你错了。主题是原子性和排序。可见性与范围有关,在这里完全不相关。
-
@user7226419:最后一次,你的词汇不合适。
标签: c multithreading volatile