1、通过共享指针获取线程返回值
int main()
{
vector<thread> vThread;
vector<int*> nRst(5);
for (size_t i = 0; i < 5; i++)
{
nRst[i] = new int(0);
}
for (int i = 0; i < 5; i++)
{
int a = 1;
int b = 2;
int *sumTemp = nRst[i];
vThread.push_back(thread([a, b, i , sumTemp]()
{
*sumTemp = (a + b + i);
}));
}
std::for_each(vThread.begin(), vThread.end(), [](thread& thr) {thr.join(); });
for (size_t i = 0; i < 5; i++)
{
delete nRst[i];
}
return 0;
}
2、使用promise+future在thread和Lambda下返回值
#include
int main()
{
int a = 1;
int b = 2;
std::promise<int> promiseObj;
std::future<int> futureObj = promiseObj.get_future();
std::thread thr = thread([a, b, &promiseObj]()
{
promiseObj.set_value(a + b);
});
thr.join();
int sum = futureObj.get();
cout << sum << endl;
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)