作者热门文章
- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
让我们说一个函数,
int fun(){
static int a = 10;
a = a+1;
return a;
}
上面的函数返回一个整数值,
//Without thread obtaining return value
#include<iostream>
int main()
{
int var = 0;
var = fun();
std::cout << "The value " << value << std::endl;
return 0;
}
现在有没有任何可能的方法来获取 C++11 线程调用时的返回值,
//Using thread
#include<iostream>
#include<thread>
int main()
{
std::thread t1(fun);//Invoking thread
//How to obtain the return value of the thread ?
return 0;
}
谢谢!
最佳答案
为了获得在后台运行的表单函数的返回值,您可能需要考虑 std::future
而不是直接创建 std::thread
目的。您可以使用 std::async()
启动一个异步任务的函数模板。它返回 std::future
最终将包含所传递函数的返回值的对象:
auto res = std::async(fun);
// ... optionally do something else
std::cout << res.get() << '\n';
也就是说,您创建一个 std::future<int>
调用std::async(func)
.然后,当你需要fun()
的返回值,您只需调用 get()
关于 future 的成员函数。如果 future 还没有准备好(即,如果它还没有结果),那么线程将阻塞直到准备好。
std::thread
std::thread
的问题是它没有提供直接机制来传输在其构造时传递的可调用对象的返回值。例如,假设您想用 std::thread
开始一个新线程使用以下函数计算两个整数之和:
int sum(int a, int b) { return a + b; }
您可能会尝试的是:
std::thread th_sum(sum, 1, 2);
// ... optionally do something else
th_sum.join();
// calculation is finished, but where is the result?
th_sum
代表的线程计算 1 和 2 的总和。但是,您没有得到 sum()
的返回值,即来自关联 std::thread
的结果对象。
相反,您可以采取的措施来解决这个问题,例如,为 sum()
创建一个包装函数有一个 out 参数作为结果而不是返回它:
void sum_outparam(int a, int b, int& res) { res = sum(a, b); }
然后,您可以在 std::ref()
的帮助下启动一个新线程来运行此包装函数。您将在 res
中获得结果:
int res;
std::thread th_sum(sum_outparam, 1, 2, std::ref(res));
// ... optionally do something else
th_sum.join();
// now, res contains the result
关于c++ - 如何从线程中获取返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57816802/
我是一名优秀的程序员,十分优秀!