[英]How to return value from std::thread
I have function that returns me a value.我有 function 返回一个值。 I want to use threads for
doSth
function and set returning value for variables above, here is an example:我想为
doSth
function 使用线程并为上面的变量设置返回值,这是一个示例:
#include <string>
#include <iostream>
#include <thread>
using namespace std;
// func for execution
int doSth(int number)
{
return number;
}
int main()
{
// some code ...
int numberOne; // no value now, but in thread I want to set a value from it
int numberTwo; // depending on function input value
thread t1(doSth, 1); // set numberOne = 1;
thread t2(doSth, 2); // set numberTwo = 2;
// wait them to execute
t1.join();
t2.join();
// now I should have numberOne = 1; numberTwo = 2
// some code ...
return 0;
}
How could I do it?我怎么能做到?
How to return value from std::thread
如何从 std::thread 返回值
Besides std::async
shown in other answers, you can use std::packaged_task
:除了其他答案中显示的
std::async
之外,您还可以使用std::packaged_task
:
std::packaged_task<int(int)> task{doSth};
std::future<int> result = task.get_future();
task(1);
int numberOne = result.get();
This allows separating creation of the task, and executing it in case that is needed.这允许分离任务的创建,并在需要时执行它。
Method 1: Using std::async
(higher-level wrapper for threads and futures):方法 1:使用
std::async
(线程和期货的高级包装器):
#include <thread>
#include <future>
#include <iostream>
int func() { return 1; }
int main(){
std::future<int> ret = std::async(&func);
int i = ret.get();
std::cout<<"I: "<<i<<std::endl;
return 0;
}
Method 2: Using threads and futures:方法2:使用线程和期货:
#include <thread>
#include <future>
#include <iostream>
void func(std::promise<int> && p) {
p.set_value(1);
}
int main(){
std::promise<int> p;
auto f = p.get_future();
std::thread t(&func, std::move(p));
t.join();
int i = f.get();
std::cout<<"I: "<<i<<std::endl;
return 0;
}
My prefered method is encapsulate the call in a specific method returning nothing (and managing error in the same way).我首选的方法是将调用封装在一个不返回任何内容的特定方法中(并以相同的方式管理错误)。
void try_doSth(int number, int* return_value, int* status)
{
try
{
*return_value = doSth(number);
*status = 0;
}
catch(const std::exception& e) { *status = 1; }
catch(...) { *status = 2; }
}
int r1,r2,s1,s2;
std::thread t1(try_doSth, 1, &r1, &s1);
std::thread t2(try_doSth, 2, &r2, &s2);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.