nurtul
nurtul

Reputation: 408

C++ Get the return value from a threaded function later

Is it possible to not wait for a return value from a threaded function? Such as checking later if the value ever returned and do something else while that function is executing? I mean it's not really multi-threading if you have to wait for the function to return because you can just straight up call the function then.

#include <thread>
#include <future>

int func_1(int x)
{ 
    return x; //Assume this takes several seconds to complete
}

int main()
{
      auto future = std::async(func_1, 2);

      int number = future.get(); //Whole program waits for this

      //More code later

      while(!number) //Check if number ever returned?
      {
            //Wait for it or assume some error/default
      }
      return 0;
}

Upvotes: 0

Views: 2795

Answers (2)

krzaq
krzaq

Reputation: 16421

You could check if the future is ready by calling future::wait_for with zero timeout and check if the returned value is equal to future_status::ready.

Btw: std::async returns special futures and you should consider if you really want to use it. More detailed info: http://scottmeyers.blogspot.com/2013/03/stdfutures-from-stdasync-arent-special.html

Upvotes: 2

Sean
Sean

Reputation: 62472

You're requesting the result immediately rather than doing something else and then getting the result when you need it. If you do this:

int main()
{
      auto future = std::async(func_1, 2);          

      //More code later

      int number = future.get(); //Whole program waits for this

      // Do something with number

      return 0;
}

Then you can do something else in the More code later bit and then block when you need the result by calling get().

Alternatively you can poll to see if the value is available using either wait_for or wait_until and do something if the result is not ready.

Upvotes: 2

Related Questions