我有一个返回值的函数。 我想对dosth
函数使用线程,并为上面的变量设置返回值,这里有一个例子:
#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;
}
我怎么能做到呢?
使用std::thread
,您可以传递一个std::promise
,将一个引用(使用std::ref()
)传递给函数以获取您的值,并使其void
。 你可以使用lambda
来玩它,就像我做的那样
或者可以使用std::async()
,下面是两个示例
int doSth(int number)
{
return number;
}
int main()
{
int numberOne, numberTwo;
std::thread t1([&]{numberOne = doSth(1);}); // set numberOne = 1;
auto f = std::async(doSth, 10);
numberTwo = f.get();
t1.join();
std::cout << numberOne << " " << numberTwo;
return 0;
}
如何从std::thread返回值
除了其他答案中显示的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();
这允许分离任务的创建,并在需要的情况下执行它。
方法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;
}
方法二:使用线程和期货:
#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;
}