简体   繁体   English

std :: future ::等待内存障碍吗? (我不能解释这个数据竞赛)

[英]Is std::future::wait a memory barrier? (I can not explain this data race)

Here is the code: 这是代码:

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;
  }
}

My question is does std::future::wait serves as a memory barrier? 我的问题是std::future::wait作为内存屏障? std::future::wait waits for the function call to complete, but does the function happens before std::future::wait (eg, does the state mutation caused by the function call visible from other threads)? std::future::wait等待函数调用完成,但函数是否发生在 std::future::wait (例如,函数调用引起的状态变异是否可以从其他线程看到)?

If std::future::wait does not serves as a memory barrier, how can we implement the threadpool so that a memory barrier is triggered automatically when the future completes? 如果std::future::wait不作为内存屏障,我们如何实现线程池,以便在将来完成时自动触发内存屏障?

Please correct me if you think my understanding of memory barrier is wrong. 如果您认为我对记忆障碍的理解是错误的,请纠正我。

[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] / 2尽管[res.on.data.races]除了vector<bool>之外 ,当同一容器中不同元素中包含的对象的内容被修改时,需要实现以避免数据争用同时。

[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. [container.requirements.dataraces] / 3 [ 注意:对于大小大于1的vector<int> xx[1] = 5*x.begin() = 10可以在没有数据竞争的情况下同时执行,但同时执行的x[0] = 5*x.begin() = 10可能导致数据争用。 As an exception to the general rule, for a vector<bool> y , y[0] = true may race with y[1] = true . 作为一般规则的例外,对于vector<bool> yy[0] = true可以与y[1] = true竞争。 —end note ] - 尾注 ]

Emphasis mine. 强调我的。 The race happens in a[i] = true; 比赛发生在a[i] = true; . vector<bool> is not a real container, accessing an "element" requires bit manipulations that touch neighboring elements. vector<bool>不是真正的容器,访问“元素”需要触摸相邻元素的位操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM