如何在c++中实现一个可组合的异步任务(Future/Promise)? (then()方法)

15次阅读

std::future 不能直接链式调用 then() 因其不可复制、无内置回调机制,强行封装易致生命周期失控或重复 get();需手写 promise/Future 结构,含 shared_state、Promise、Future 三部分,并用 shared_ptr 管理状态、mutex 保护写入、vector 存回调。

如何在c++中实现一个可组合的异步任务(Future/Promise)? (then()方法)

为什么 std::future 不能直接链式调用 then()

标准库std::future 没有 then() 方法,且是**不可复制**(仅可移动),无法在回调中安全持有并转发。强行包装会导致生命周期失控、std::future::get() 被重复调用或阻塞线程。真正可组合的异步任务需要自己管理状态流转和执行上下文。

手写 Promise/Future 的最小可行结构

核心是三部分:共享状态(shared_state)、Promise(写端)、Future(读端 + then)。所有回调必须延迟到前序任务完成后再调度,且每个 then 返回新 Future

  • shared_statestd::shared_ptr 管理,含 std::optional 存结果、std::mutex 保护写入、std::vector<:function>> 存待触发的 then 回调
  • Promise::set_value(T) 锁定后设置值,并逐个调用已注册的回调(注意:回调里可能再调 then,所以需拷贝回调列表)
  • Future::then(F&& f) 注册一个新回调,该回调接收当前值、返回 Future,内部自动把返回的 Futureshared_state 和当前绑定

then() 回调如何处理返回值类型和异常

模板推导必须支持 f 返回 TFuture 或抛异常。关键点是:无论 f 返回什么,都要统一“降级”为 Future;异常要捕获并存入下游 shared_state

template auto then(F&& f) && {     using R = std::invoke_result_t;     auto next_promise = Promise>{};     auto next_future = next_promise.get_future();      state_->add_continuation([p = std::move(next_promise), f = std::forward(f)](auto&& val) mutable {         try {             if constexpr (std::is_same_v>>) {                 auto inner_fut = f(std::forward(val));                 inner_fut.state_->link_to(p.state_); // 链式转发完成状态             } else {                 p.set_value(f(std::forward(val)));             }         } catch (...) {             p.set_exception(std::current_exception());         }     });      return std::move(next_future); }

实际使用时最容易漏掉的三件事

不是语法问题,而是语义陷阱:

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

  • 没有显式调度策略:所有 then 回调默认在「前序任务完成的线程」执行,若前序是 IO 线程而你想切到 GUI 线程,必须手动加 post(ui_executor, ...)
  • Future 移动后原对象变空,但 state_ 仍被其他 Future 引用,所以不能靠析构来释放资源 —— 必须用引用计数保证 shared_state 生命周期
  • 循环引用风险:若 then 回调里又捕获了当前 Future(比如用于重试),就会导致 shared_state 永远不销毁,必须用 weak_ptr 或明确设计生命周期边界

c++20 的 std::jthread 和协程能简化调度,但 then() 的本质逻辑——状态传递、错误传播、类型擦除——还是得自己兜底。别指望靠一层 wrapper 就完全复刻 rustasync/await 流畅度。

text=ZqhQzanResources