在C++11及之后的标准中,std::promise和std::future是异步编程模型里的核心组件,主要用于在不同线程之间传递异步任务的结果,避免传统线程同步中繁琐的锁操作。std::promise负责在一个线程中设置任务的结果或者异常,std::future则可以在另一个线程中获取这个结果,两者通过共享状态关联,实现线程间安全的数据传递。

核心概念解析
std::promise的作用
std::promise是一个模板类,它可以在某个线程中存储一个值或者一个异常,这个值或异常后续会被关联的std::future对象获取。当我们创建了一个std::promise对象之后,就可以通过它的成员函数set_value设置结果,或者通过set_exception设置异常,一旦设置完成,关联的共享状态就会变为就绪状态,等待结果的线程就可以获取到对应内容。
std::future的作用
std::future同样是模板类,它用来获取异步操作的结果。我们可以通过std::promise的get_future成员函数得到对应的std::future对象,然后调用future的get成员函数来阻塞等待结果就绪,一旦结果就绪就返回对应的值。如果不想阻塞等待,也可以调用wait_for或者wait_until来设置等待超时时间。
基础使用示例
下面通过一个简单的例子展示std::promise和std::future的基本配合流程,我们在子线程中计算两个数的和,然后将结果通过promise传递给主线程,主线程通过future获取结果。
#include <iostream>
#include <thread>
#include <future>
#include <stdexcept>
// 子线程执行的任务函数,接收promise对象,计算结果后设置到promise中
void calculate_task(std::promise<int> prom, int a, int b) {
try {
// 模拟耗时计算
std::this_thread::sleep_for(std::chrono::seconds(1));
int result = a + b;
// 设置计算结果到promise
prom.set_value(result);
} catch (...) {
// 如果出现异常,将异常设置到promise中
prom.set_exception(std::current_exception());
}
}
int main() {
// 创建promise对象,存储int类型的结果
std::promise<int> prom;
// 获取关联的future对象
std::future<int> fut = prom.get_future();
// 创建子线程,传入promise对象和计算参数,注意promise不能拷贝,需要转移所有权
std::thread t(calculate_task, std::move(prom), 10, 20);
// 主线程阻塞等待结果
try {
int result = fut.get();
std::cout << "异步计算结果为: " << result << std::endl;
} catch (const std::exception& e) {
std::cout << "捕获到异常: " << e.what() << std::endl;
}
// 等待子线程执行完成
t.join();
return 0;
}
运行上述代码,主线程会等待1秒左右,然后输出异步计算结果为30,说明子线程的结果成功传递到了主线程。
关键注意事项
- std::promise对象不支持拷贝构造和拷贝赋值,只能移动,因此在传递给线程函数的时候需要使用std::move转移所有权,否则会导致编译错误。
- std::future的get函数只能调用一次,多次调用会抛出std::future_error异常,因为获取结果之后共享状态就会被释放。
- 如果promise对象在销毁之前没有设置过值或者异常,那么关联的future调用get的时候会抛出std::future_error异常,错误码为std::future_errc::broken_promise。
- 如果需要多次获取异步结果,可以使用std::shared_future,它支持多个线程同时获取结果,并且get函数可以多次调用。
结合std::async简化使用
在实际开发中,如果不想手动创建promise和线程,也可以使用std::async来更简洁地实现异步操作,std::async内部会自动创建promise和future,并且管理线程的创建和销毁。
#include <iostream>
#include <future>
// 异步执行的任务函数
int async_task(int a, int b) {
std::this_thread::sleep_for(std::chrono::seconds(1));
return a * b;
}
int main() {
// 使用std::async启动异步任务,返回future对象
std::future<int> fut = std::async(async_task, 5, 6);
// 获取结果
int result = fut.get();
std::cout << "异步任务结果为: " << result << std::endl;
return 0;
}
这种方式比手动使用std::promise和std::thread更简洁,适合大多数不需要精细控制线程的场景。
std::promisestd::futureC++多线程异步编程修改时间:2026-07-19 02:39:10