std::promise 是类模板 ,可以在某个线程中给它赋值,然后在其他线程中取值。
#include<iostream>
#include<future>
using namespace std;
void myThread(std::promise<int> &temp, int num)
{
cout << "Thread start id = " << this_thread::get_id() << endl;
chrono::milliseconds time(5000); //休息5秒
this_thread::sleep_for(time);
temp.set_value(num *2); //将结果保存在promise对象中
cout << "Thread end id = " << this_thread::get_id() << endl;
}
int main()
{
cout << "Main start id = " << this_thread::get_id() << endl;
promise<int> promise; //promise对象中保存值类型为int
thread thread(myThread, ref(promise),5);
thread.join();
future<int> result = promise.get_future(); //获取结果值
cout << "result = " << result.get() << endl;
return 0;
}
执行结果: