C++ std::future与std::promise使用详解
作者:ClearCorner
时间:2025-11-07
浏览:0
std::future和std::promise用于线程间传递数据,promise设置一次结果,future获取该结果并支持异常传递,需注意只能设置一次且get后失效。
std::future和std::promise用于线程间传递数据,promise设置一次结果,future获取该结果并支持异常传递,需注意只能设置一次且get后失效。

在C++中,std::future 和 std::promise 是用于线程间传递数据的重要工具。它们配合使用,可以实现一个线程计算结果,另一个线程获取结果的功能。
基本概念说明
std::promise 是一个可写入一次的对象,用来保存某个值或异常。每个 promise 与一个共享状态相关联,可以通过它设置结果。
std::future 是一个只读对象,用来获取 promise 设置的结果。它可以等待结果就绪,并通过 get() 方法取出值。
基本用法示例
下面是一个简单的例子,展示如何在一个线程中通过 promise 设置值,在主线程中通过 future 获取:
#include#include #include void setValue(std::promise && p) { std::this_thread::sleep_for(std::chrono::seconds(2)); p.set_value(42); // 设置结果 } int main() { std::promise prms; std::future fut = prms.get_future(); // 获取对应的 future std::thread t(setValue, std::move(prms)); std::cout << "等待结果...\n"; int value = fut.get(); // 阻塞直到结果可用 std::cout << "得到结果: " << value << "\n"; t.join(); return 0; }
异常传递
除了正常值,promise 还可以设置异常,future 在 get() 时会抛出该异常:
void setException(std::promise&& p) { try { throw std::runtime_error("出错了!"); } catch (...) { p.set_exception(std::current_exception()); } }
调用 fut.get() 时会重新抛出这个异常,需用 try-catch 捕获。
注意事项
- 每个 promise 只能 set_value 或 set_exception 一次,重复调用会导致程序终止。
- 如果 promise 被销毁前未设置值,future.get() 会抛出 broken_promise 异常。
- future 的 get() 方法只能调用一次,之后其值变为无效。
- 移动语义常用:promise 和 future 都不支持拷贝,只能移动。
作者最新文章
多张图片转PDF教程:在线批量合成与顺序调整技巧
2026-09-03 10:03
AutoCAD 2014安装指南:环境检查、授权配置与首次启动设置
2026-09-02 13:34
watchstore下载软件教程:设备兼容、安装流程与常见故障
2026-09-02 13:24
PDF转Word免费方法及编辑可行性判断指南
2026-09-01 18:14
魅族20pro怎么样 魅族20pro参数配置
2026-08-25 15:42
上一篇:
铁路12306查历史车票步骤详解
热门文章
更多
精品专题
更多
Mac软件
更多
WINDOWS
更多


































