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

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

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() 会重新抛出该异常,避免错误被静默吞掉。

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

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),此处通常不出现
// 等待最多 500ms
if (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 线程即可。