使用std::future需要包含<future>头文件:
#include <future>
通常通过std::async函数来创建一个std::future对象,std::async用于启动一个异步任务。例如:
#include <iostream>
#include <future>
// 一个简单的函数,用于异步执行
int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; ++i) {
result *= i;
}
return result;
}
int main() {
// 启动一个异步任务,计算5的阶乘
std::future<int> result = std::async(factorial, 5);
// 这里可以做其他的工作,而不必等待异步任务完成
std::cout << "继续执行其他任务..." << std::endl;
// 获取异步任务的结果,这会阻塞当前线程,直到任务完成
int factorial_result = result.get();
std::cout << "5的阶乘是: " << factorial_result << std::endl;
return 0;
}
在上述代码中,std::async(factorial, 5)启动了一个异步任务来计算 5 的阶乘,并返回一个std::future<int>对象,通过调用result.get()可以获取异步任务的计算结果。
std::future有三种状态:
可以通过std::future_status枚举来检查std::future的状态,使用wait_for函数:
#include <iostream>
#include <future>
#include <chrono>
int main() {
std::future<int> result = std::async([]() {
std::this_thread::sleep_for(std::chrono::seconds(2));
return 42;
});
// 等待任务完成,最多等待1秒
auto status = result.wait_for(std::chrono::seconds(1));
if (status == std::future_status::ready) {
std::cout << "任务已完成,结果是: " << result.get() << std::endl;
} else if (status == std::future_status::timeout) {
std::cout << "等待超时,任务尚未完成" << std::endl;
} else if (status == std::future_status::deferred) {
std::cout << "任务被延迟执行" << std::endl;
}
return 0;
}
如果异步任务抛出异常,result.get()会重新抛出该异常,我们可以通过try-catch块来捕获异常:
#include <iostream>
#include <future>
int throw_exception() {
throw std::runtime_error("发生了一个运行时错误");
return 42;
}
int main() {
std::future<int> result = std::async(throw_exception);
try {
int value = result.get();
} catch (const std::exception& e) {
std::cout << "捕获到异常: " << e.what() << std::endl;
}
return 0;
}
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有