5

If a function has a non-void return value and I join it using the .join function then is there any way to retrieve its return value?

Here is a simplified example:

float myfunc(int k)
{
  return exp(k);
}

int main()
{
  std::thread th=std::thread(myfunc, 10);

  th.join();

  //Where is the return value?
}
Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Reza
  • 388
  • 2
  • 14
  • Possible duplicate of [C++: Simple return value from std::thread?](https://stackoverflow.com/questions/7686939/c-simple-return-value-from-stdthread) – Axalo Nov 17 '17 at 17:04

2 Answers2

6

You can follow this sample code to get the return value from a thread :-

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

In short, .get() gets the return value, you can typecast and use it then.

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
Asim
  • 1,430
  • 1
  • 22
  • 43
3

my own solution:

#include <thread>
void function(int value, int *toreturn)
{
 *toreturn = 10;
}

int main()
{
 int value;
 std::thread th = std::thread(&function, 10, &value);
 th.join();
}
Kevin Agusto
  • 56
  • 1
  • 5