C++如何使用std::future和std::promise进行线程间通信?(代码示例)

std::future和std::promise是C++11提供的单次值线程间传递机制:promise通过set_value/set_exception写入结果,future通过get/wait_for读取,共享状态自动同步,仅可移动不可拷贝。

c++如何使用std::future和std::promise进行线程间通信?(代码示例)

std::future 和 std::promise 是 C++11 引入的用于在线程间传递单次值的配套机制:promise 负责“设置”结果,future 负责“获取”结果。它们不共享内存,而是通过一个共享状态(shared state)解耦生产者与消费者,适合一对一线程通信或异步任务结果传递。

基本配对用法:一个线程设值,另一个取值

promise 对象持有可写入的共享状态,调用 set_value() 后,绑定的 future 就能通过 get() 安全读取(若未就绪则阻塞)。注意:每个 promise/future 对只能使用一次,且不能拷贝(仅可移动)。

// 示例:主线程等待子线程计算完成

#include #include #include int main() {    std::promise prom;    std::future fut = prom.get_future(); // 获取关联的 future    std::thread t([&prom]() {        // 模拟耗时计算        std::this_thread::sleep_for(std::chrono::seconds(1));        prom.set_value(42); // 设置结果(只能调用一次)    });    std::cout << "等待结果...n";    int result = fut.get(); // 阻塞直到 set_value 被调用    std::cout << "得到结果:" << result << "n";    t.join();    return 0;}

处理异常:用 set_exception 传递错误

如果异步操作可能失败,promise 支持通过 set_exception 传递异常对象,future 的 get() 会重新抛出该异常,避免错误被静默吞掉。

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

// 在子线程中捕获异常并转发

std::thread t([&prom]() {    try {        throw std::runtime_error("计算失败");    } catch (...) {        prom.set_exception(std::current_exception()); // 转发当前异常    }});try {    int x = fut.get(); // 这里会抛出 runtime_error} catch (const std::exception& e) {    std::cout << "捕获异常:" << e.what() << "n";}

非阻塞检查:wait_for 与 wait_until

future 提供超时等待能力,避免无限阻塞。wait_for 返回 std::future_status 枚举值,可用于轮询或带超时的同步逻辑。

std::future_status::ready:值已就绪(set_value 或 set_exception 已调用) std::future_status::timeout:超时,尚未就绪 std::future_status::deferred:仅适用于 std::async(launch::deferred),此处通常不出现

// 等待最多 500msif (fut.wait_for(std::chrono::milliseconds(500)) == std::future_status::ready) {    std::cout << "成功获取:" << fut.get() << "n";} else {    std::cout << "超时,任务未完成n";}

与 std::async 配合更简洁(但语义不同)

std::async 会自动创建 promise/future 对,并启动异步任务。它返回的 future 也支持 get()、wait_for 等操作,但底层调度由实现决定(可能延迟执行)。若需精确控制线程生命周期或手动触发,仍应显式使用 promise/future。

// 等效但更简短(内部仍用 promise/future 实现)auto fut2 = std::async(std::launch::async, []() -> int {    std::this_thread::sleep_for(std::chrono::seconds(1));    return 123;});std::cout << "async 结果:" << fut2.get() << "n";

基本上就这些。核心是理解 promise 是“写端”,future 是“读端”,共享状态自动管理线程安全——你不用加锁,get() 和 set_value() 内部已同步。注意别重复 set、别跨线程拷贝 promise/future、及时 join 或 detach 线程即可。

以上就是C++如何使用std::future和std::promise进行线程间通信?(代码示例)的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1488814.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 11:53:20
下一篇 2025年12月19日 11:53:37

相关推荐

发表回复

登录后才能评论
关注微信