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 ;
}

最新文章

  1. Hibernate的关联映射关系
  2. 博客 博客vno主题(我正在用的这个博客主题)
  3. MySQL 添加列, 修改列, 删除列
  4. IOS学习资源收集--开发UI控件相关
  5. Animation Play/Stop测试
  6. SQL Server查询优化方法(查询速度慢的原因很多,常见如下几种) .
  7. css link和@import区别用法
  8. linux下无线网卡的ioctl 接口
  9. Junit3.8 Stack测试
  10. Altium Designer快捷键 【worldsing笔记】
  11. 微软在.NET官网上线.NET 架构指南频道
  12. C# To C++ Converter Cracked ( 破解版 )
  13. 一个农民工混迹于 IT 行业多年后的泣血总结
  14. Quartz公共类,log4net 日志分目录 ,调度任务。
  15. new 经典基础模板总结
  16. centos7 下通过yum安装JDK
  17. loj#2665. 「NOI2013」树的计数
  18. Leetcode 870. 优势洗牌
  19. Java入门开发POI读取导入Excel文件
  20. Virtual Memory$$memory-mapped-files

热门文章

  1. Linux 内核之api_man 手册安装
  2. python 装饰器 (多个装饰器装饰一个函数---装饰器前套一个函数)
  3. 渗透测试实验(i春秋 真的很简单)
  4. poj 2393 奶牛场生产成本问题 贪心算法
  5. ubuntu配置机器学习环境(四) 安装intel MKL
  6. P2966 [USACO09DEC]牛收费路径Cow Toll Paths
  7. 位运算 &amp; 网络序字节序
  8. Linux-Shell脚本编程-学习-5-Shell编程-使用结构化命令-if-then-else-elif
  9. 关键词提取TF-IDF算法/关键字提取之TF-IDF算法
  10. Structure From Motion(SFM,从运动恢复结构)