C++ std::promise cppreference

std::promise 主要用在多线程的线程通信上,可以将promise<int> 用作线程间信号。

获取结果
	- get_future    返回与承诺的结果关联的 future
						(公开成员函数)
						
设置结果
	- set_value 				设置结果为指定值
								(公开成员函数)
								
	- set_value_at_thread_exit 	设置结果为指定值,同时仅在线程退出时分发提醒
										(公开成员函数)
										
	- set_exception				设置结果为指示异常
									(公开成员函数)
									
	- set_exception_at_thread_exit	设置结果为指示异常,同时仅在线程退出时分发提醒
									(公开成员函数)

#include <vector>
#include <thread>
#include <future>
#include <numeric>
#include <iostream>
#include <chrono>
 
void accumulate(std::vector<int>::iterator first,
                std::vector<int>::iterator last,
                std::promise<int> accumulate_promise)
{
    int sum = std::accumulate(first, last, 0);
    accumulate_promise.set_value(sum);  // 提醒 future
}
 
void do_work(std::promise<void> barrier)
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    barrier.set_value();
}
 
int main()
{
    // 演示用 promise<int> 在线程间传递结果。
    std::vector<int> numbers = { 1, 2, 3, 4, 5, 6 };
    std::promise<int> accumulate_promise;
    std::future<int> accumulate_future = accumulate_promise.get_future();
    std::thread work_thread(accumulate, numbers.begin(), numbers.end(),
                            std::move(accumulate_promise));
 
    // future::get() 将等待直至该 future 拥有合法结果并取得它
    // 无需在 get() 前调用 wait()
    //accumulate_future.wait();  // 等待结果
    std::cout << "result=" << accumulate_future.get() << '\n';
    work_thread.join();  // wait for thread completion
 
    // 演示用 promise<void> 在线程间对状态发信号
    std::promise<void> barrier;
    std::future<void> barrier_future = barrier.get_future();
    std::thread new_work_thread(do_work, std::move(barrier));
    barrier_future.wait();
    new_work_thread.join();
}
  • 用 std::async 来做简单的事情,例如异步执行一个任务。但是要注意 std::future 析构阻塞的问题。
  • std::packaged_task 能够很轻松的拿到 std::future,选择是否配合 std::thread 进行异步处理。同时没有析构阻塞的问题。
  • std::promise 是三者中最底层的能力,可以用来同步不同线程之间的消息
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值