Can one retrieve the return value of a thread function in C++11?

跟風遠走 提交于 2020-12-06 06:58:05

问题


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

回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/47355735/can-one-retrieve-the-return-value-of-a-thread-function-in-c11

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!