可以在C ++ 11中检索线程函数的返回值吗? [英] Can one retrieve the return value of a thread function in C++11?

查看:48
本文介绍了可以在C ++ 11中检索线程函数的返回值吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个函数具有非无效的返回值,而我使用 .join 函数将其加入,那么有什么方法可以检索它的返回值?

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?

这是一个简化的示例:

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

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

  th.join();

  //Where is the return value?
}

推荐答案

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

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

简而言之,.get()获得返回值,您可以键入并使用它.

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

这篇关于可以在C ++ 11中检索线程函数的返回值吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆