首页 > 后端开发 > C++ > 正文

c++怎么使用future和promise_future与promise异步编程指南

裘德小鎮的故事
发布: 2025-10-08 21:08:01
原创
143人浏览过
std::future和std::promise用于线程间异步传递结果,其中promise设置值,future获取值,实现同步;可通过thread、async或packaged_task结合使用,注意set_value只能调用一次,get()后值被移动,且需避免未设置值时销毁promise。

c++怎么使用future和promise_future与promise异步编程指南

在C++中,std::futurestd::promise 是实现异步编程的重要工具,它们属于标准库中的 <future> 头文件。通过这两个机制,可以在一个线程中设置值,另一个线程中获取该值,实现线程间的数据传递和结果同步。

1. 基本概念:future 与 promise 的作用

std::promise 是一个可写入一次的对象,用于保存某个操作的结果。每个 promise 可以关联一个 std::future,future 是读取端,用来获取 promise 设置的值或异常。

简单来说:

  • promise 负责“生产”数据(set_value 或 set_exception)
  • future 负责“消费”数据(get)

一旦值被设置,future 的 get() 就能返回结果;如果还没准备好,get() 会阻塞等待。

立即学习C++免费学习笔记(深入)”;

2. 创建并使用 promise 和 future

下面是基本用法示例:

// 示例:主线程等待子线程完成任务并返回结果 #include <iostream> #include <thread> #include <future> void compute(std::promise<int>& result) { try { // 模拟耗时计算 std::this_thread::sleep_for(std::chrono::seconds(2)); int value = 42; result.set_value(value); // 设置结果 } catch (...) { result.set_exception(std::current_exception()); } } int main() { std::promise<int> prom; std::future<int> fut = prom.get_future(); // 获取对应的 future std::thread t(compute, std::ref(prom)); std::cout << "等待结果...\n"; int result = fut.get(); // 阻塞直到值可用 std::cout << "结果是: " << result << "\n"; t.join(); return 0; }

说明:

燕雀Logo
燕雀Logo

为用户提供LOGO免费设计在线生成服务

燕雀Logo 101
查看详情 燕雀Logo
  • 创建 std::promise<int> 来准备传递一个整型结果
  • 调用 get_future() 获取其对应的 future 对象
  • 将 promise 引用传给子线程函数,在其中设置结果
  • 主线程调用 fut.get() 等待并获取结果

3. 使用 async 和 packaged_task 替代手动管理线程

除了直接配合线程使用,future 还可以结合 std::asyncstd::packaged_task 实现更简洁的异步调用。

// 使用 std::async 自动启动异步任务 #include <iostream> #include <future> int heavy_calculation() { std::this_thread::sleep_for(std::chrono::seconds(2)); return 84; } int main() { std::future<int> fut = std::async(heavy_calculation); std::cout << "正在计算...\n"; int result = fut.get(); std::cout << "计算完成,结果为: " << result << "\n"; return 0; }

这里 std::async 返回一个 future,自动处理线程生命周期,适合简单场景。

另一种方式是 packaged_task,它把可调用对象包装成带 future 的任务:

std::packaged_task<int()> task(heavy_calculation); std::future<int> fut = task.get_future(); std::thread t(std::move(task)); // 启动任务 int result = fut.get(); // 获取结果 t.join();

这种方式更灵活,可用于事件队列、线程池等复杂结构。

4. 注意事项与常见问题

使用 future 和 promise 时需注意以下几点:

  • 每个 promise 只能调用一次 set_valueset_exception,重复调用会抛出异常
  • 如果 promise 被销毁前未设置值,future 的 get() 会收到 std::future_error
  • future 的 get() 只能调用一次,之后不能再用(值已被移动)
  • 可以用 wait_forwait_until 实现超时检查,避免无限等待
auto status = fut.wait_for(std::chrono::milliseconds(100)); if (status == std::future_status::ready) { std::cout << "结果已就绪: " << fut.get() << "\n"; } else { std::cout << "还在处理中...\n"; }

这比直接阻塞更安全,适用于需要响应性的程序。

基本上就这些。掌握 future 和 promise 能帮助你写出清晰、高效的异步代码,尤其在多线程协作和任务解耦方面非常有用。

以上就是c++++怎么使用future和promise_future与promise异步编程指南的详细内容,更多请关注php中文网其它相关文章!

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号