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

问题描述 投票:2回答:2

如果函数具有非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?
}
c++ multithreading c++11 stdthread
2个回答
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;
}

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


0
投票

我自己的解决方案

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

int main()
{
 int value;
 std::thread th = std::thread(&function, 10, &value);
 th.join();
}
© www.soinside.com 2019 - 2024. All rights reserved.