std::async是C++中用于简化异步任务执行的工具,通过返回std::future获取结果,支持std::launch::async(新线程执行)和std::launch::deferred(延迟执行)两种策略,默认由系统决定;可传递函数参数或使用lambda表达式,并能捕获异常以保证安全。
在C++中,std::async 是实现异步调用的重要工具之一,它允许你以简单的方式启动一个任务并在后台执行,而无需手动管理线程。通过 std::async,你可以方便地获取任务的返回值,并控制任务的执行策略。
基本用法:使用 std::async 启动异步任务
std::async 是定义在
示例:
#include#include int compute() { return 42; }
int main() { auto future = std::async(compute); int result = future.get(); // 阻塞等待结果 std::cout << "Result: " << result << std::endl; return 0; }
在这个例子中,compute() 函数在后台执行,调用 future.get() 时主线程会等待直到结果可用。
执行策略:选择 async 还是 defer
std::async 支持两种执行策略:
- std::launch::async:强制在新线程中执行任务。
- std::launch::deferred:延迟执行,直到调用 get() 或 wait() 才在当前线程运行。
你可以显式指定策略:
auto future1 = std::async(std::launch::async, compute); // 异步执行 auto future2 = std::async(std::launch::deferred, compute); // 延迟执行 auto future3 = std::async(std::launch::async | std::launch::deferred, compute); // 让系统决定
如果不指定,默认行为由系统决定,可能是异步也可能是延迟执行。
传递参数与使用 lambda
你可以向 std::async 传递参数,就像调用普通函数一样:
int add(int a, int b) {
return a + b;
}
auto future = std::async(add, 5, 3);
std::cout << "Sum: " << future.get() << std::endl;
也可以使用 lambda 表达式封装更复杂的逻辑:
auto future = std::async([](int x) {
return x * x;
}, 10);
std::cout << "Square: " << future.get() << std::endl;
异常处理与资源管理
如果异步任务抛出异常,该异常会被捕获并存储在 future 中。当你调用 get() 时,异常会被重新抛出。
auto future = std::async([] {
throw std::runtime_error("Something went wrong");
});
try {
future.get();
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}

务必使用 try-catch 捕获可能的异常,避免程序崩溃。
基本上就这些。std::async 提供了简洁的方式来执行并发任务,适合大多数需要异步计算的场景。不复杂但容易忽略的是执行策略的选择和异常的安全处理。合理使用 future 和 async,能显著提升程序响应性和资源利用率。









