我有一个生成多个线程的程序,这些线程可能会将完全相同的值写入完全相同的内存位置:
std::vector<int> vec(32, 1); // Initialize vec with 32 times 1
std::vector<std::thread> threads;
for (int i = 0 ; i < 8 ; ++i) {
threads.emplace_back([&vec]() {
for (std::size_t j = 0 ; j < vec.size() ; ++j) {
vec[j] = 0;
}
});
}
for (auto& thrd: threads) {
thrd.join();
}
在这个简化的代码中,所有线程都可能尝试将完全相同的值写入 vec
中的相同内存位置。 .这是一场可能触发未定义行为的数据竞争,还是安全的,因为在所有线程再次加入之前从未读取值?
如果存在潜在危险的数据竞争,将使用 std::vector<std::atomic<int>>
而不是 std::memory_order_relaxed
商店足以防止数据竞争?
最佳答案
语言律师回答,[intro.multithread] n3485
21 The execution of a program contains a data race if it contains two conflicting actions in different threads, at least one of which is not atomic, and neither happens before the other. Any such data race results in undefined behavior.
4 Two expression evaluations conflict if one of them modifies a memory location and the other one accesses or modifies the same memory location.
will using a
std::vector<std::atomic<int>>
instead withstd::memory_order_relaxed
stores instead be enough to prevent the data races?
是的。这些访问是原子的,并且通过线程的连接引入了一种发生在之前的关系。从产生这些工作线程的线程(通过 .join
同步)的任何后续读取都是安全和定义的。
关于c++ - 并行写入相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23043251/