Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 583
peter55555 Avatar asked Apr 19 '16 23:04

peter55555


1 Answers

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.

like image 114
M.M Avatar answered Oct 05 '22 15:10

M.M