贝利信息

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

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

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

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

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

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

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