c++ - 并行写入相同的值

标签 c++ multithreading c++11 race-condition memory-model

我有一个生成多个线程的程序,这些线程可能会将完全相同的值写入完全相同的内存位置:

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 with std::memory_order_relaxed stores instead be enough to prevent the data races?

是的。这些访问是原子的,并且通过线程的连接引入了一种发生在之前的关系。从产生这些工作线程的线程(通过 .join 同步)的任何后续读取都是安全和定义的。

关于c++ - 并行写入相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23043251/

相关文章:

C++ 静态运算符重载

c++ - 两个类——如何从另一个类访问一个类的对象?

c++ - 在 C++ 结构中重载运算符 << 和 >>

c++ - 如何在运行时使用静态成员函数初始化静态成员变量?

java - GWT(服务器端)可以多线程

c++ - 在 Win32 上如何将线程移动到另一个 CPU 核心?

c++ - 关闭应用程序是否释放在 C++ 中使用 new 分配的空间?

c++ - Qt 4.8 - 更新 QGraphicsScene 时显示 “loading” 动画

c++ - 首先是 std::remove_reference 还是 std::remove_cv?

c++ - C++ 中的简单复制构造函数