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

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

最佳答案

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

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() 获取返回值,您可以类型转换并使用它。

关于c++ - 可以检索 C++11 中线程函数的返回值吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47355735/

相关文章:

multithreading - 如何才能充分利用 .NET 4.0 中新增强的并行功能?

c++11 结合 std::tuple 和 std::tie 以实现高效排序

c++ - 如何使用 lambda 删除空 vector 单元格?

c++ - dynamic_cast 如何失败?

c++ - 队列实现的 Malloc 指针错误

c++ - 多线程应用程序中的死锁检测

Python,多线程太慢,多进程

c++ - Qt - 为什么第一个和第二个 QKeyEvent 之间有 500 毫秒的延迟?

android - 了解 Android 服务和线程

java - 在 C++ 中模拟 Java 枚举