std::async 是C++中用于简化异步任务的机制,通过返回 std::future 获取结果,支持 async 和 deferred 两种执行策略,可控制任务是否异步或延迟执行;它能传递返回值和异常,适用于并行计算多个独立任务,提升程序并发效率与响应性。
在C++中,std::async 是一种基于任务的并发机制,能够简化异步调用的编写。它允许你以更高级的方式启动一个任务,而无需手动管理线程的创建与生命周期。通过 std::async,你可以将一个函数“扔”到后台执行,并在需要结果时通过 std::future 获取返回值,整个过程清晰且易于控制。
std::async 接受一个可调用对象(如函数、lambda表达式或函数对象),并返回一个 std::future 对象,用于访问异步操作的结果。
示例代码:
#include#include int compute() { return 42; } int main() { auto future = std::async(compute); std::cout << "Result: " << future.get() << "\n"; // 输出 42 return 0; }
std::async 支持两种启动策略:
指定策略示例:
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_ta
sk_b(); });
int result1 = f1.get(); // 等待第一个任务
int result2 = f2.get(); // 等待第二个任务
std::cout << "Results: " << result1 << ", " << result2 << "\n";
这种模式适用于独立的耗时操作,比如加载资源、网络请求或数值计算。
基本上就这些。std::async 提供了一种简洁、安全的方式来处理异步任务,避免了直接操作线程的复杂性。合理使用它可以显著提升程序响应性和资源利用率。不复杂但容易忽略的是策略选择和异常安全。