【发布时间】:2020-12-08 11:43:40
【问题描述】:
给定下面的代码,能保证看到 a 的最新值 4 吗?
int a;
mutex mtx;
void f() {
unique_lock<mutex> lck(mtx);
// read(a);
// is it guarantee it will see the value 4?
}
int main() {
a = 4;
thread(f);
}
【问题讨论】:
-
在全局变量的第一步值中,将设置a,一旦它创建的线程就可以看到设置的值。
-
分配
a = 4;在thread(f);生成之前完成。因此,这是有保证的。 (AFAIK,启动线程就足够同步了。)如果a在启动线程后从未更改,则甚至不需要锁。 -
在您的代码 sn-p 中,即使没有互斥锁也可以保证。
-
函数定义位置不影响代码执行顺序。
-
为什么不呢?即使没有线程,你的代码也会做同样的事情
标签: c++ multithreading