Is it safe to return from a function before all std :: futures are complete?

I have a code like this:

int function() { std::vector<std::future<int>> futures; for (const auto& elem : elements) { futures.push_back(std::async(&MyClass::foo, myClass, elem); } for (auto& f : futures) { const int x = f.get(); if (x != 0) return x; } } 

Is it possible to return from a function when there are incomplete asynchronous calls? I am only interested in one non-zero value. Should I wait for all asynchronous calls to complete? Is this code safe?

+5
source share
1 answer

The std::future destructor (when initialized from a call to std::async ) is blocked until the async task completes. ( See here )

This way your return will not be completed until all tasks are completed.

+7
source

Source: https://habr.com/ru/post/1247479/


All Articles