一、说明
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时间不一样,导致的输出不一样。
6429

被折叠的 条评论
为什么被折叠?



