I have code like that:
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;
}
}
Can I return from function when there are unfinished async calls? I'm interested only in one non zero value. Should I wait until all async calls are finished? Is this code safe?
The destructor of std::future
(when initialized from a call to std::async
) blocks until the async task is complete. (See here)
So your function return
statement will not complete until all of the tasks have finished.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With