[英]C++ storing std::future form std::async in vector and wating for all
I want to do several tasks in parallel with std::async and then wait until all the futures have completed.我想与 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;
}
But when executing the program i get an std::future_error
thrown:但是在执行程序时,我得到一个
std::future_error
抛出:
terminate called after throwing an instance of 'std::future_error'
what(): std::future_error: No associated state
Aborted (core dumped)
And i wonder why.我想知道为什么。 Shouldnt I be able to store the future objects?
我不应该能够存储未来的对象吗?
You initialized your handles
array with 5 default-constructed elements, then you emplaced 5 more into it.您使用 5 个默认构造的元素初始化了您的
handles
数组,然后又在其中放置了 5 个。 It now has 10 elements, the first 5 of which are default-constructed and therefore not associated with anything to wait for.它现在有 10 个元素,其中前 5 个是默认构造的,因此不与任何等待相关联。
Don't create the vector with 5 elements.不要创建包含 5 个元素的向量。 I think you were trying to reserve space for 5 elements - this can be done by calling
reserve
after the vector is constructed.我认为您试图为 5 个元素保留空间- 这可以通过在构造向量后调用
reserve
来完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.