std::future和std::promise用于线程间异步传递结果,其中promise设置值,future获取值,实现同步;可通过thread、async或packaged_task结合使用,注意set_value只能调用一次,get()后值被移动,且需避免未设置值时销毁promise。

在C++中,std::future 和 std::promise 是实现异步编程的重要工具,它们属于标准库中的 <future> 头文件。通过这两个机制,可以在一个线程中设置值,另一个线程中获取该值,实现线程间的数据传递和结果同步。
std::promise 是一个可写入一次的对象,用于保存某个操作的结果。每个 promise 可以关联一个 std::future,future 是读取端,用来获取 promise 设置的值或异常。
简单来说:
一旦值被设置,future 的 get() 就能返回结果;如果还没准备好,get() 会阻塞等待。
立即学习“C++免费学习笔记(深入)”;
下面是基本用法示例:
// 示例:主线程等待子线程完成任务并返回结果 #include <iostream> #include <thread> #include <future> void compute(std::promise<int>& result) { try { // 模拟耗时计算 std::this_thread::sleep_for(std::chrono::seconds(2)); int value = 42; result.set_value(value); // 设置结果 } catch (...) { result.set_exception(std::current_exception()); } } int main() { std::promise<int> prom; std::future<int> fut = prom.get_future(); // 获取对应的 future std::thread t(compute, std::ref(prom)); std::cout << "等待结果...\n"; int result = fut.get(); // 阻塞直到值可用 std::cout << "结果是: " << result << "\n"; t.join(); return 0; }说明:
std::promise<int> 来准备传递一个整型结果get_future() 获取其对应的 future 对象fut.get() 等待并获取结果除了直接配合线程使用,future 还可以结合 std::async 或 std::packaged_task 实现更简洁的异步调用。
// 使用 std::async 自动启动异步任务 #include <iostream> #include <future> int heavy_calculation() { std::this_thread::sleep_for(std::chrono::seconds(2)); return 84; } int main() { std::future<int> fut = std::async(heavy_calculation); std::cout << "正在计算...\n"; int result = fut.get(); std::cout << "计算完成,结果为: " << result << "\n"; return 0; }这里 std::async 返回一个 future,自动处理线程生命周期,适合简单场景。
另一种方式是 packaged_task,它把可调用对象包装成带 future 的任务:
std::packaged_task<int()> task(heavy_calculation); std::future<int> fut = task.get_future(); std::thread t(std::move(task)); // 启动任务 int result = fut.get(); // 获取结果 t.join();这种方式更灵活,可用于事件队列、线程池等复杂结构。
使用 future 和 promise 时需注意以下几点:
set_value 或 set_exception,重复调用会抛出异常std::future_error
wait_for 或 wait_until 实现超时检查,避免无限等待这比直接阻塞更安全,适用于需要响应性的程序。
基本上就这些。掌握 future 和 promise 能帮助你写出清晰、高效的异步代码,尤其在多线程协作和任务解耦方面非常有用。以上就是c++++怎么使用future和promise_future与promise异步编程指南的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号