我想知道如果我想立即读取从该线程存储的值,是否需要在线程连接后放置内存屏障。线程连接是否已经暗示了内存屏障?
vector<int> v(1 << 21);
thread th([&]() {
for (int i = 0; i < (1 << 20); i++) {
v[i] = i * 123; // store some kind of calculation results into the vector
}
});
for (int i = (1 << 20); i < (1 << 21); i++) {
v[i] = i * 123;
}
th.join();
// Is any memory fence needed to be here?
// use the values from another thread...
printf("%d\n", v[1234]);
// ...
最佳答案
不需要。不需要内存围栏,因为thread::join
会阻塞,直到执行线程完成执行为止。另外,运行循环后,连接操作由主线程执行。我看不到联接操作后将如何需要隔离墙。
关于c++ - 在没有任何锁的情况下加入另一个线程后是否需要内存防护?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59418860/