一、概要
promise实现跨线程设置和获取值,底层使用了mutex来保证设置值的原子性,通过future实现了跨线程等待获取结果。
二、代码
#pragma once
#include <future>
#include <thread>
#include <chrono>
#include <iostream>
using namespace std;
class PromiseTest
{
private:
promise<int> p;
void process()
{
this_thread::sleep_for(chrono::seconds(5));
p.set_value(20);
}
public:
void doTest()
{
future<int> f = p.get_future();
thread t1([this]() {
this->process(); });
t1.detach();
while (f.wait_for(chrono::seconds(1)) != future_status::ready)
{
cout << "wait for result" << endl;
}
int r = f.get();
cout << "result=" << r << endl;
}
};
三、输出
wait for result
wait for result
wait for result
wait for result
result=20