c++ - std::future::wait 是内存屏障吗? (我无法解释这个数据竞赛)

标签 c++ multithreading c++11

代码如下:

std::vector<bool> a(req_count_);
std::vector<std::future<void>> waits(req_count_);

for (int i = 0; i < req_count_; i++) {
  // send into a threadpool implementation
  waits[i] = framework::Async([i, &a] {
    a[i] = true; // write true
  });
}

for (int i = 0; i < req_count_; i++) {
  waits[i].wait(); // memory barrier?
}

int last_req_count = req_count_;
req_count_ = 0;

for (int i = 0; i < last_req_count; i++) {
  if (!a[i]) { // read false
    return false;
  }
}

我的问题是 std::future::wait 是否用作内存屏障? std::future::wait 等待函数调用完成,但函数是否发生在 std::future::wait (例如,由其他线程可见的函数调用引起的状态突变)?

如果 std::future::wait 不作为内存屏障,我们如何实现线程池以便在 future 完成时自动触发内存屏障?

如果您认为我对内存屏障的理解有误,请指正。

最佳答案

[container.requirements.dataraces]/2 Notwithstanding [res.on.data.races], implementations are required to avoid data races when the contents of the contained object in different elements in the same container, excepting vector<bool>, are modified concurrently.

[container.requirements.dataraces]/3 [ Note: For a vector<int> x with a size greater than one, x[1] = 5 and *x.begin() = 10 can be executed concurrently without a data race, but x[0] = 5 and *x.begin() = 10 executed concurrently may result in a data race. As an exception to the general rule, for a vector<bool> y, y[0] = true may race with y[1] = true. —end note ]

强调我的。比赛发生在 a[i] = true; . vector<bool>不是真正的容器,访问“元素”需要接触相邻元素的位操作。

关于c++ - std::future::wait 是内存屏障吗? (我无法解释这个数据竞赛),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48452611/

相关文章:

c++ - SOIL_load_image() 返回 null

c++使用数组作为参数时出现free错误

c++ - 基于模板参数的可选范围检查

c++ - 从元组派生类

c++ - 使用模板化 comp 函数实现 unique_copy - 类型推断

c++ - 等待所有线程完成一项工作然后再做另一项

c++ - 我的代码中的 HMAC-SHA512 错误

c++ - QTimer的方法 'isActive()'是线程安全的吗?

python - 创建可访问 app_globals 的 Pylons 线程

c - 线程函数返回是否需要 pthread_join?