[英]Can one retrieve the return value of a thread function in C++11?
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? 如果函数具有非无效的返回值,而我使用
.join
函数将其加入,那么有什么方法可以检索其返回值?
Here is a simplified example: 这是一个简化的示例:
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;
}
In short, .get() gets the return value, you can typecast and use it then. 简而言之,.get()获取返回值,您可以键入并使用它。
my own solution: 我自己的解决方案:
#include <thread>
void function(int value, int *toreturn)
{
*toreturn = 10;
}
int main()
{
int value;
std::thread th = std::thread(&function, 10, &value);
th.join();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.