future
std::future 是 C++11 提供的异步结果容器,用来接收某个异步任务最终返回的值或异常。它通常和 std::promise、std::async、std::packaged_task 配合使用。
它的核心意义是把“任务的执行”和“结果的获取”分开:生产者负责写入结果,消费者负责等待并读取结果。
头文件与基本特征
使用 future 时,通常包含:
#include <future>
主要特征:
| 特征 | 说明 |
|---|---|
| 角色 | 表示异步计算的最终结果 |
| 数据来源 | 常见于 promise、async、packaged_task |
| 读取方式 | get() 获取结果,wait() 等待完成 |
| 结果类型 | 可以是值、引用、void,也可以传播异常 |
| 所有权 | 普通 future 只能被取走一次 |
基本用法
promise 和 future
std::promise 负责写入结果,std::future 负责读取结果:
#include <future>
#include <iostream>
#include <thread>
int main() {
std::promise<int> prom;
std::future<int> fut = prom.get_future();
std::thread worker([&prom]() {
prom.set_value(42);
});
std::cout << fut.get() << '\n';
worker.join();
return 0;
}
get() 会等待结果可用,然后返回值。对于普通 future,get() 只能调用一次。
async 和 future
std::async 可以直接启动异步任务并返回 future:
#include <future>
#include <iostream>
int slowAdd(int a, int b) {
return a + b;
}
int main() {
auto fut = std::async(std::launch::async, slowAdd, 10, 20);
std::cout << fut.get() << '\n';
return 0;
}
交互演示(MDX + React)
下面这个面板用于演示 wait()、get()、异常传播,以及 shared_future 的多次读取能力。
std::future 状态演示
演示 wait、get、异常传播,以及 shared_future 的多次读取能力。
状态idle
模式future
valid()true
future 尚未就绪。
最近操作
- 初始化: promise/future 处于 idle 状态
常用成员函数
| 函数 | 作用 |
|---|---|
get() | 获取结果,若未就绪会阻塞,普通 future 只能调用一次 |
wait() | 等待结果就绪 |
wait_for() | 等待指定时长 |
wait_until() | 等待到指定时间点 |
valid() | 判断 future 是否仍然有效 |
get()
get() 用来获取最终结果:
std::future<int> fut = std::async(std::launch::async, [] {
return 100;
});
int value = fut.get();
如果异步任务保存的是异常,get() 会重新抛出该异常。
wait()
wait() 只等待完成,不取走结果:
std::future<int> fut = std::async(std::launch::async, [] {
return 100;
});
fut.wait();
int value = fut.get();
shared_future
普通 future 只能移动不能复制。如果需要多个消费者读取同一个结果,可以把它转成 shared_future:
#include <future>
int main() {
auto fut = std::async(std::launch::async, [] { return 7; });
std::shared_future<int> sf = fut.share();
int a = sf.get();
int b = sf.get();
return 0;
}
shared_future 可以多次 get(),适合广播式读取同一个结果。
wait_for 和 wait_until
这两个接口适合做超时等待。
#include <future>
#include <chrono>
std::future<int> fut = std::async(std::launch::async, [] {
return 42;
});
if (fut.wait_for(std::chrono::seconds(1)) == std::future_status::ready) {
int value = fut.get();
}
返回状态通常有三种:
| 状态 | 含义 |
|---|---|
future_status::ready | 已就绪 |
future_status::timeout | 超时 |
future_status::deferred | 延迟执行,尚未真正开始 |
常见场景
- 后台任务执行完成后,把结果传回主线程。
- 需要限制等待时间的异步调用。
- 一个结果需要被多个读取者共享时,用
shared_future。 - 把耗时计算从主流程中拆出去,提升响应速度。
使用注意
- 普通
future的get()只能调用一次。 get()可能阻塞,不要在不合适的线程里长时间等待。- 如果需要多次读取,使用
shared_future。 - 记得处理异常,异步错误会在
get()时重新抛出。 wait_for()/wait_until()适合超时控制,不适合替代真正的结果获取。
小结
std::future 是 C++11 异步编程的结果接收端,适合和 promise、async、packaged_task 配合使用。掌握 get()、wait()、超时等待和 shared_future 之后,就能覆盖绝大多数基础异步任务场景。