5

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?

peter55555
  • 1,413
  • 1
  • 19
  • 36
  • What does "safe" mean? – Kerrek SB Apr 19 '16 at 23:29
  • I mean crash, undefined behavior or something like that. I just want to get first non zero value and ignore others. I want my program to always behave like that. In other words - are there any dangers in this code? I don't know what will happen when others async calls will be finished and `vector` of futures will not exist. – peter55555 Apr 19 '16 at 23:32
  • 6
    Your program does not have undefined behaviour. But it may block on the completion of all asynchronous operations before returning. – Kerrek SB Apr 19 '16 at 23:33
  • 6
    Destructor of `std::future` blocks until the async task completes ([see here](http://stackoverflow.com/questions/23455104/why-is-the-destructor-of-a-future-returned-from-stdasync-blocking)) – M.M Apr 19 '16 at 23:34
  • It means that function stops in return instruction, waits until all tasks are completed and after that returns my found first non-zero `x`? So code is ok but processing `function()` will take as much time as all async tasks are completed? – peter55555 Apr 19 '16 at 23:42
  • 1
    @KerrekSB May? Must. (except for non-conforming compilers) – Yakk - Adam Nevraumont Apr 20 '16 at 03:53
  • @Yakk: The functions could all have returned already, or the implementation could have chosen the deferred policy. In neither case would there be "blocking" in the sense of the OS scheduler, non? – Kerrek SB Apr 20 '16 at 08:15

1 Answers1

7

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.

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365