std::async可用于异步执行函数并获取结果,支持指定启动策略如std::launch::async或deferred,能捕获异常并通过future.get()重新抛出,适合简单并发任务。

在C++中,std::async 是进行异步编程的便捷工具,它能让你在一个单独的线程中运行函数,并通过 std::future 获取其返回结果。相比直接使用 std::thread,它更灵活且易于管理返回值和异常。
使用 std::async 启动一个异步任务非常简单。你只需要传入一个可调用对象(比如函数、lambda表达式等),它会返回一个 std::future 对象,用于获取结果。
#include <iostream>
#include <future>
#include <chrono>
int long_computation() {
std::this_thread::sleep_for(std::chrono::seconds(2));
return 42;
}
int main() {
// 启动异步任务
std::future<int> future_result = std::async(long_computation);
std::cout << "正在执行其他操作...\n";
// 获取结果(会阻塞直到完成)
int result = future_result.get();
std::cout << "结果是: " << result << "\n";
return 0;
}
std::async 支持两种启动策略:
默认情况下,系统可以自由选择策略。你可以显式指定:
立即学习“C++免费学习笔记(深入)”;
// 强制异步执行
auto future1 = std::async(std::launch::async, long_computation);
// 延迟执行
auto future2 = std::async(std::launch::deferred, []() {
std::cout << "这个函数只在 get() 调用时执行\n";
return 100;
});
// future2.get(); // 此时才会执行
如果异步任务抛出异常,该异常会被捕获并存储。当你调用 future.get() 时,异常会重新抛出。
void may_throw() {
throw std::runtime_error("出错了!");
}
int main() {
auto future = std::async(may_throw);
try {
future.get(); // 异常在这里重新抛出
} catch (const std::exception& e) {
std::cout << "捕获异常: " << e.what() << "\n";
}
return 0;
}
你可以同时启动多个异步任务,分别获取它们的 future,然后逐个获取结果。
int task1() { std::this_thread::sleep_for(std::chrono::seconds(1)); return 10; }
int task2() { std::this_thread::sleep_for(std::chrono::seconds(2)); return 20; }
int main() {
auto f1 = std::async(std::launch::async, task1);
auto f2 = std::async(std::launch::async, task2);
std::cout << "等待两个任务完成...\n";
int r1 = f1.get();
int r2 = f2.get();
std::cout << "总和: " << r1 + r2 << "\n"; // 输出 30
return 0;
}
基本上就这些。使用 std::async 可以快速实现简单的异步计算任务,适合不需要精细线程控制的场景。注意它不适用于长期运行的服务线程或需要频繁通信的情况。合理使用启动策略和异常处理,能让异步代码更健壮。
以上就是c++++怎么使用std::async进行异步编程_c++ std::async异步编程方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号