std::async 是C++中用于简化异步任务的机制,通过返回 std::future 获取结果,支持 async 和 deferred 两种执行策略,可控制任务是否异步或延迟执行;它能传递返回值和异常,适用于并行计算多个独立任务,提升程序并发效率与响应性。

在C++中,std::async 是一种基于任务的并发机制,能够简化异步调用的编写。它允许你以更高级的方式启动一个任务,而无需手动管理线程的创建与生命周期。通过 std::async,你可以将一个函数“扔”到后台执行,并在需要结果时通过 std::future 获取返回值,整个过程清晰且易于控制。
std::async 接受一个可调用对象(如函数、lambda表达式或函数对象),并返回一个 std::future 对象,用于访问异步操作的结果。
示例代码:
#include <future>
#include <iostream>
int compute() {
return 42;
}
int main() {
auto future = std::async(compute);
std::cout << "Result: " << future.get() << "\n"; // 输出 42
return 0;
}
std::async 支持两种启动策略:
立即学习“C++免费学习笔记(深入)”;
指定策略示例:
auto future1 = std::async(std::launch::async, [] {
// 必须在新线程中运行
return heavy_computation();
});
auto future2 = std::async(std::launch::deferred, [] {
// 只有调用 get() 时才会执行
return simple_calc();
});
std::future 不仅能传递返回值,还能传播异常。如果异步任务抛出异常,调用 future.get() 时会重新抛出该异常。
示例:
auto future = std::async([] {
throw std::runtime_error("Something went wrong");
});
try {
future.get();
} catch (const std::exception& e) {
std::cout << "Caught: " << e.what() << "\n";
}
你可以同时启动多个 std::async 任务,然后分别获取结果,实现并行计算。
auto f1 = std::async([] { return expensive_task_a(); });
auto f2 = std::async([] { return expensive_task_b(); });
int result1 = f1.get(); // 等待第一个任务
int result2 = f2.get(); // 等待第二个任务
std::cout << "Results: " << result1 << ", " << result2 << "\n";
这种模式适用于独立的耗时操作,比如加载资源、网络请求或数值计算。
基本上就这些。std::async 提供了一种简洁、安全的方式来处理异步任务,避免了直接操作线程的复杂性。合理使用它可以显著提升程序响应性和资源利用率。不复杂但容易忽略的是策略选择和异常安全。
以上就是c++++如何使用std::async简化异步调用_c++基于任务的并发的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号