线程--promise furture 同步
2024-09-27 14:48:19
http://www.cnblogs.com/haippy/p/3279565.html
std::promise 类介绍
promise 对象可以保存某一类型 T 的值,该值可被 future 对象读取(可能在另外一个线程中),因此 promise 也提供了一种线程同步的手段。在 promise 对象构造时可以和一个共享状态(通常是std::future)相关联,并可以在相关联的共享状态(std::future)上保存一个类型为 T 的值。
可以通过 get_future 来获取与该 promise 对象相关联的 future 对象,调用该函数之后,两个对象共享相同的共享状态(shared state)
- promise 对象是异步 Provider,它可以在某一时刻设置共享状态的值。
- future 对象可以异步返回共享状态的值,或者在必要的情况下阻塞调用者并等待共享状态标志变为 ready,然后才能获取共享状态的值。
#include <iostream> // std::cout
#include <functional> // std::ref
#include <thread> // std::thread
#include <future> // std::promise, std::future void print_int(std::future<int>& fut) {
int x = fut.get(); // 获取共享状态的值.
std::cout << "value: " << x << '\n'; // 打印 value: 10.
} int main ()
{
std::promise<int> prom; // 生成一个 std::promise<int> 对象.
std::future<int> fut = prom.get_future(); // 和 future 关联.
std::thread t(print_int, std::ref(fut)); // 将 future 交给另外一个线程t.
prom.set_value(); // 设置共享状态的值, 此处和线程t保持同步.
t.join();
return ;
}
#include <iostream> // std::cin, std::cout, std::ios
#include <functional> // std::ref
#include <thread> // std::thread
#include <future> // std::promise, std::future
#include <exception> // std::exception, std::current_exception void get_int(std::promise<int>& prom) {
int x;
std::cout << "Please, enter an integer value: ";
std::cin.exceptions(std::ios::failbit); // throw on failbit
try {
std::cin >> x; // sets failbit if input is not int
prom.set_value(x);
}
catch (std::exception&) {
prom.set_exception(std::current_exception());
}
} void print_int(std::future<int>& fut) {
try {
int x = fut.get();
std::cout << "value: " << x << '\n';
}
catch (std::exception& e) {
std::cout << "[exception caught: " << e.what() << "]\n";
}
} int main()
{
std::promise<int> prom;
std::future<int> fut = prom.get_future(); std::thread th1(get_int, std::ref(prom));
std::thread th2(print_int, std::ref(fut)); th1.join();
th2.join();
return ;
}
最新文章
- Hibernate的关联映射关系
- 博客 博客vno主题(我正在用的这个博客主题)
- MySQL 添加列, 修改列, 删除列
- IOS学习资源收集--开发UI控件相关
- Animation Play/Stop测试
- SQL Server查询优化方法(查询速度慢的原因很多,常见如下几种) .
- css link和@import区别用法
- linux下无线网卡的ioctl 接口
- Junit3.8 Stack测试
- Altium Designer快捷键 【worldsing笔记】
- 微软在.NET官网上线.NET 架构指南频道
- C# To C++ Converter Cracked ( 破解版 )
- 一个农民工混迹于 IT 行业多年后的泣血总结
- Quartz公共类,log4net 日志分目录 ,调度任务。
- new 经典基础模板总结
- centos7 下通过yum安装JDK
- loj#2665. 「NOI2013」树的计数
- Leetcode 870. 优势洗牌
- Java入门开发POI读取导入Excel文件
- Virtual Memory$$memory-mapped-files
热门文章
- Linux 内核之api_man 手册安装
- python 装饰器 (多个装饰器装饰一个函数---装饰器前套一个函数)
- 渗透测试实验(i春秋 真的很简单)
- poj 2393 奶牛场生产成本问题 贪心算法
- ubuntu配置机器学习环境(四) 安装intel MKL
- P2966 [USACO09DEC]牛收费路径Cow Toll Paths
- 位运算 &; 网络序字节序
- Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif
- 关键词提取TF-IDF算法/关键字提取之TF-IDF算法
- Structure From Motion(SFM,从运动恢复结构)