I want to do several tasks in parallel with std::async and then wait until all the futures have completed.
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:
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. It now has 10 elements, the first 5 of which are default-constructed and therefore not associated with anything to wait for.
Don't create the vector with 5 elements. I think you were trying to reserve space for 5 elements - this can be done by calling reserve
after the vector is constructed.