gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:17:25 24 4
gpt4 key购买 nike

代码如下:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com