在没有任何锁的情况下加入另一个线程后是否需要内存屏障?

问题描述 投票:1回答:1

我想知道如果我想立即读取从该线程存储的值,是否需要在线程连接后放置内存屏障。线程连接是否已经暗示内存屏障?

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]);
// ...
c++ multithreading c++11
1个回答
1
投票

没有不需要内存屏障,因为thread::join将阻塞直到执行线程完成执行。同样,加入操作由运行循环的主线程after执行。我看不到联接操作后如何需要隔离墙。

© www.soinside.com 2019 - 2024. All rights reserved.