【问题标题】:Can one retrieve the return value of a thread function in C++11?可以在 C++11 中检索线程函数的返回值吗?
【发布时间】:2017-11-17 16:59:35
【问题描述】:

如果一个函数有一个非 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


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我自己的解决方案:

    #include <thread>
    void function(int value, int *toreturn)
    {
     *toreturn = 10;
    }
    
    int main()
    {
     int value;
     std::thread th = std::thread(&function, 10, &value);
     th.join();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多