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


版权声明:本文为qq_41058468原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。