A future is an object that can retrieve a value from some provider object or function, properly synchronizing this access if in different threads.

provider比较抽象,可以是函数可以是类,是别人提供好的东西

A promise is an object that can store a value of type T to be retrieved by a future object (possibly in another thread), offering a synchronization point.

future用于访问异步操作结果

std::async可以异步执行函数,可能是放到另一个线程去执行,返回值是一个future类型

std::promise用于线程同步的工具,储存一些数据,供future获取,协程在运行得到结果后也会将结果写入promise供获取

以async为例

代码来源

#include <iostream>             // std::cout
#include <future> // std::async, std::future
#include <chrono> // std::chrono::milliseconds // a non-optimized way of checking for prime numbers:
bool is_prime(int x)
{
for (int i = 2; i < x; ++i)
if (x % i == 0)
return false;
return true;
} int main()
{
// call function asynchronously:
std::future < bool > fut = std::async(is_prime, 6666661); // do something while waiting for function to set future:
std::cout << "checking, please wait";
std::chrono::milliseconds span(100);
while (fut.wait_for(span) == std::future_status::timeout)
std::cout << '.'; bool x = fut.get(); // retrieve return value std::cout << "\n6666661 " << (x ? "is" : "is not") << " prime.\n"; return 0;
}

后面C++20里的协程我猜应该是基于此实现的,理解一下有好处

这里放一下官方promise的代码

#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';
} int main ()
{
std::promise<int> prom; // create promise std::future<int> fut = prom.get_future(); // engagement with future std::thread th1 (print_int, std::ref(fut)); // send future to new thread prom.set_value (10); // 模拟fulfill promise
// (synchronizes with getting the future)
th1.join();
return 0;
}

最新文章

  1. 迭代字典中的key和value
  2. Spark基础知识汇总
  3. Project、Target、Workspace and Scheme
  4. C# CGI程序
  5. 学习BFC
  6. Windows Server 2003下ASP.NET无法识别IE11的解决方法【转】
  7. Rman实现数据库迁移
  8. COJ 2004 序列
  9. SGU 415. Necessary Coins ( 背包dp )
  10. hdu1561(树形dp)
  11. UVA 11636-Hello World!(水题,猜结论)
  12. RabbitMQ在Windows环境下的安装与使用
  13. Django 之缓存
  14. 文件批量上传-统一附件管理器-在线预览文件(有互联网和没有两种)--SNF快速开发平台3.0
  15. 轮询、中断、DMA和通道
  16. No caching ——无缓存工具
  17. POJ 3253 Fence Repair (哈夫曼树)
  18. Java线程池关闭1-shutdown和isTerminated&lt;转&gt;
  19. ArcGIS案例学习笔记2_1
  20. chrome 调试跨域iframe

热门文章

  1. OneinStack基础搭建typecheo轻量级博客
  2. java中使用 MultipartFile 进行文件上传而且指定了上传的临时路径,但是文件上传成功后,显示临时文件 无法删除为什么
  3. springcloud 和springboot版本对比
  4. 网络爬虫Python(一)
  5. springboot Elasticsearch 实体创建索引设置Date 类型字段失败
  6. T137288 铸星
  7. 使用Mybatis plus xml 记录过程
  8. Axure的认识与使用
  9. pands 编码知识
  10. ChatGPT检测器开发者在知乎的文章,记录一下