代码如下:
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, butx[0] = 5
and*x.begin() = 10
executed concurrently may result in a data race. As an exception to the general rule, for avector<bool> y
,y[0] = true
may race withy[1] = true
. —end note ]
强调我的。比赛发生在 a[i] = true;
. vector<bool>
不是真正的容器,访问“元素”需要接触相邻元素的位操作。
关于c++ - std::future::wait 是内存屏障吗? (我无法解释这个数据竞赛),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48452611/