std::promise,std::future和std::packaged_task

#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()会阻塞当前线程

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值