可以在C++ 11中检索线程函数的返回值吗?

Rez*_*eza 2 c++ multithreading c++11 stdthread

如果函数具有非void返回值并且我使用该.join函数将其连接,那么有没有办法检索它的返回值?

这是一个简化的例子:

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

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

  th.join();

  //Where is the return value?
}
Run Code Online (Sandbox Code Playgroud)

Asi*_*sim 5

您可以按照此示例代码从线程获取返回值: -

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;
}
Run Code Online (Sandbox Code Playgroud)

简而言之,.get()获取返回值,然后可以进行类型转换并使用它.