std::async是C++11提供的异步任务启动工具,通过指定启动策略(如launch::async或launch::deferred)执行函数或lambda,并返回future对象获取结果,支持参数传递与引用捕获,简化多线程编程。

std::async 是 C++11 引入的一个用于异步执行任务的工具,定义在
std::async 基本用法
std::async 接受一个可调用对象(如函数、lambda 表达式、函数对象等)作为参数,自动创建一个异步任务。你可以选择任务的启动策略,也可以让系统自行决定。
基本语法:
std::future其中:
立即学习“C++免费学习笔记(深入)”;
- launch::policy:启动策略,可选 launch::async(强制异步执行)、launch::deferred(延迟执行,在 get 或 wait 时才运行),或不指定(由系统决定)。
- callable:要异步执行的函数或 lambda。
- args...:传递给 callable 的参数。
获取异步结果
std::async 返回一个 std::future 对象,可以通过调用它的 get() 方法来获取异步函数的返回值。get() 是阻塞调用,会等待任务完成。
示例:
#include iostream>#include
int slow_task() {
std::this_thread::sleep_for(std::chrono::seconds(2));
return 42;
}
int main() {
auto future = std::async(slow_task);
std::cout int result = future.get(); // 等待完成并获取结果
std::cout return 0;
}
启动策略详解
std::async 支持两种主要策略:
- launch::async:立即在新线程中运行任务。
- launch::deferred:不创建新线程,任务延迟到 future::get 或 future::wait 被调用时才执行。
如果不指定策略,系统可以自由选择。例如:
auto f1 = std::async(std::launch::async, [](){ return do_work(); }); // 一定异步auto f2 = std::async(std::launch::deferred, [](){ return do_work(); }); // 延迟执行
auto f3 = std::async([](){ return do_work(); }); // 系统决定
使用 Lambda 和参数传递
std::async 可以配合 lambda 使用,也支持传参:
auto future = std::async([](int x, int y) {return x + y;
}, 5, 3);
std::cout
注意:参数默认按值传递。若需引用,使用 std::ref:
void modify_value(int& x) { x *= 2; }int val = 10;
auto future = std::async(modify_value, std::ref(val));
future.get(); // val 现在是 20
基本上就这些。std::async 提供了一种简洁的异步编程方式,适合不需要手动管理线程的场景。关键在于理解 launch 策略和 future 的行为,避免意外的阻塞或资源问题。不复杂但容易忽略细节。











