nurtul nurtul - 2 months ago 8
C++ Question

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;
}

Answer

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.

Comments