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