std::future 与 std::promise
future 获取异步结果、promise 设置值、packaged_task、async 启动
std::future 与 std::promise
future/promise 是线程间传递值的高层抽象——一个线程设置结果,另一个等待获取。
学完本章你将: 掌握 future 获取异步结果、promise 设置值、async 启动。
promise → future 通信
cpp
#include <future>
#include <thread>
void worker(std::promise<int> p) {
// 模拟计算
std::this_thread::sleep_for(std::chrono::seconds(1));
p.set_value(42); // 设置结果
}
int main() {
std::promise<int> p;
std::future<int> f = p.get_future();
std::thread t(worker, std::move(p));
std::cout << "等待结果...\n";
int result = f.get(); // 阻塞直到结果就绪
std::cout << "结果: " << result << "\n"; // 42
t.join();
}
std::async —— 一行启动异步
cpp
// 异步启动——返回值是 future
auto future = std::async(std::launch::async, []() {
std::this_thread::sleep_for(std::chrono::seconds(1));
return 42;
});
// 做其他事情...
std::cout << "结果: " << future.get() << "\n"; // 阻塞并获取
packaged_task
cpp
// 把可调用对象包装成 future
std::packaged_task<int(int, int)> task([](int a, int b) {
return a + b;
});
std::future<int> result = task.get_future();
task(3, 5); // 执行任务
std::cout << result.get(); // 8
future 状态
cpp
f.valid(); // future 是否关联了共享状态
f.wait(); // 阻塞等待结果
f.wait_for(3s); // 等待一段时间
auto status = f.wait_for(0s); // future_status::ready/timeout/deferred
f.get(); // 获取结果(只能调用一次!)