#std::promise
std::promise是一个模板类: template<typename R> class promise。其泛型参数R为std::promise对象保存的值的类型,R可以是void类型。std::promise保存的值可被与之关联的std::future读取,读取操作可以发生在其它线程。std::promise允许move语义(右值构造,右值赋值),但不允许拷贝(拷贝构造、赋值),std::future亦然。std::promise和std::future合作共同实现了多线程间通信。
#例子
#include <iostream> // std::cout, std::endl
#include <thread> // std::thread
#include <string> // std::string
#include <future> // std::promise, std::future
#include <chrono> // seconds
#include <windows.h>
using namespace std::chrono;
void read(std::future<std::string> *future) {
Sleep(2000); //停2s
std::cout << future->get() << std::endl; //CODE1,future会一直阻塞,直到有值到来
}
int main() {
std::promise<std::string> promise; // promise 相当于生产者
std::future<std::string> future = promise.get_future(); // future 相当于消费者, 右值构造,与promise关联
std::thread thread(read, &future); // thread开始执行
promise.set_value("hello future"); // promise设置,CODE1但不会被执行,此時read还在等待2s中,2s末才执行CODE1
// 让thread等5s,这里read里面开始了2s倒计时,这里又开始thread的5s倒计时
// read开始倒计时比thread开始倒计时快一点点,但read先thread后
std::this_thread::sleep_for(seconds(5));
thread.join(); // thread设为jion模式
std::cout << "main" << std::endl; //CODE2,等待thread结束,才执行下面CODE2
system("pause");
return 0;
}
// 控制台第2s末输出: hello future
//控制台第5s末输出: main
总的来说,时序如下
#include <future> // std::promise, std::future
#include <chrono> // seconds
#include <windows.h>
using namespace std::chrono;
void write(std::promise<std::string> *prom) {
Sleep(2000); // 然后停2s
prom->set_value("hello future"); //promise设值
}
int main() {
std::promise<std::string> promise; // promise 相当于生产者
std::thread thread(write, &promise); //线程thread开始
std::cout << promise.get_future().get() << std::endl; //一直阻塞,2s末promise设值,输出hello future,之后下面才执行
std::this_thread::sleep_for(seconds(5)); // thread停5s
thread.join(); // 等待线程执行完成
std::cout << "main" << std::endl; //7s后输出main
system("pause");
return 0;
}
// 控制台第2s末输出: hello future
//控制台第7s末输出: main
注意点:future.get()会阻塞当前线程