【cmu15445c++入门】(13)C++的std::promise

一、说明

 std::promise 是C++11并发编程中常用的一个类,常配合std::future使用。其作用是在一个线程t1中保存一个类型typename T的值,可供相绑定的std::future对象在另一线程t2中获取

二、代码

#include <chrono>
#include <future>
#include <iostream>
#include <numeric>
#include <thread>
#include <vector>

void accumulate(int task_cost_second, std::promise<int> accumulate_promise) {
  std::cout << "before set_value" << std::endl;
  std::this_thread::sleep_for(std::chrono::seconds(task_cost_second));
  accumulate_promise.set_value(task_cost_second);  // 提醒 future
  std::cout << "after set_value" << std::endl;
}

void accumulate2(int task_cost_second, std::promise<int> accumulate_promise) {
  std::cout << "before set_value" << std::endl;
  std::this_thread::sleep_for(std::chrono::seconds(task_cost_second));
  accumulate_promise.set_value(task_cost_second);  // 提醒 future
  std::cout << "after set_value" << std::endl;
}

int main() {
  // 用 promise<int> 在线程间传递结果。
  std::cout << "**********第一个测试**********" << std::endl;
  std::promise<int> accumulate_promise;
  std::future<int> accumulate_future = accumulate_promise.get_future();
  std::thread work_thread(accumulate, 3, std::move(accumulate_promise));

  // future::get() 将等待直至该 future 拥有合法结果并取得它
  // 无需在 get() 前调用 wait()
  // accumulate_future.wait();  // 等待结果
  std::cout << "before accumulate_future.get()" << std::endl;
  std::this_thread::sleep_for(std::chrono::seconds(5));
  std::cout << "result=" << accumulate_future.get() << '\n';
  std::cout << "ater accumulate_future.get()" << std::endl;
  work_thread.join();  // wait for thread completion

  // 演示用 promise<void> 在线程间对状态发信号
  std::cout << "**********第二个测试**********" << std::endl;
  std::promise<int> accumulate_promise1;
  std::future<int> accumulate_future1 = accumulate_promise1.get_future();
  std::thread work_thread1(accumulate2, 3, std::move(accumulate_promise1));

  // future::get() 将等待直至该 future 拥有合法结果并取得它
  // 无需在 get() 前调用 wait()
  // accumulate_future.wait();  // 等待结果
  std::cout << "before accumulate_future.get()" << std::endl;
  std::this_thread::sleep_for(std::chrono::seconds(1));
  std::cout << "result=" << accumulate_future1.get() << '\n';
  std::cout << "ater accumulate_future.get()" << std::endl;
  work_thread1.join();  // wait for thread completion
}

 三、结果

 不难发现两个测试用例线程的sleep时间不一样,导致的输出不一样。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

康雨城

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值