学习C++:学习promise和future的使用

promise和future

C++11使用std::future和std::promise在线程中传递变量实现异步操作。

网上找到的示意图:
在这里插入图片描述

promise成员函数:

  1. std::promise::get_future
  2. std::promise::set_value
  3. std::promise::set_exception
  4. std::promise::set_value_at_thread_exit: 在线程退出时该 promise 对象会自动设置为 ready(注意:该线程已设置promise的值,如果在线程结束之后有其他修改共享状态值的操作,会抛出future_error(promise_already_satisfied)异常)
  5. std::promise::swap:交换 promise 的共享状态

std::future常用function:

  1. std::future::get: 获取值
  2. std::future::wait: 等待状态为ready,无返回值
  3. std::future::wait_for: 等待一段时间,返回std::future_status

std::future_status三种状态:

  1. deferred:异步操作还没开始
  2. ready:异步操作已经完成
  3. timeout:异步操作超时
#include <iostream>
#include <thread>
#include <future>
#include <chrono>

int main() {
  std::promise<int> p;
  std::thread thread_([&p]{
    std::cout << "thead_id: " << std::this_thread::get_id() << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(1));
    p.set_value(10);
  });
  std::cout << "main thread_id: " << std::this_thread::get_id() << std::endl;
  std::future_status status;
  auto f= p.get_future();
  //调用get()会阻塞直到状态为ready
  //auto v = f.get();
  //std::cout << "v: " << v << std::endl;
  do {
    status = f.wait_for(std::chrono::milliseconds(100));
    if (status == std::future_status::timeout) {
      std::cout << "timeout..." << std::endl;
    } else if (status == std::future_status::ready) {
      int val = f.get();
      std::cout << "ready, val: " << val << std::endl;
    } else {
      std::cout << "other..." << std::endl;
    }
  } while (status != std::future_status::ready);
  thread_.join();
  return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值