C++在向量中存储std::future形式的std::async并等待所有人
我想与 std::async 并行执行多项任务,然后等到所有期货都完成。
void update() {
// some code here
}
int main() {
std::vector<std::future<void>> handles(5);
for (int i = 0; i < 5; ++i) {
auto handle = std::async(std::launch::async, &update);
handles.emplace_back(std::move(handle));
}
for (auto& handle : handles) {
handle.wait();
}
return 0;
}
但是在执行程序时,我得到了一个std::future_error抛出:
terminate called after throwing an instance of 'std::future_error'
what(): std::future_error: No associated state
Aborted (core dumped)
我想知道为什么。我不应该能够存储未来的对象吗?
回答
你handles用 5 个默认构造的元素初始化了你的数组,然后你又在其中放置了 5 个。它现在有 10 个元素,其中前 5 个元素是默认构造的,因此与任何要等待的元素无关。
不要创建具有 5 个元素的向量。我认为您试图为 5 个元素保留空间- 这可以通过reserve在构造向量后调用来完成。
THE END
二维码