在 C11 中引入的std::async是一个用于异步执行任务的工具它简化了多线程编程的复杂度通过返回std::future对象实现对异步任务结果的获取。​​一、核心概念​​std::async用于启动一个异步任务可能在独立线程中执行并返回一个std::future对象通过该对象可以阻塞等待任务完成并获取返回值future::get()查询任务状态future::valid()、future::wait_for()等异常传递任务中的异常会延迟到get()时抛出。​​二、函数原型与启动策略​​std::async的声明如下1234567templateclassFunction,class... Args std::futuretypenamestd::result_ofFunction(Args...)::typeasync( Function f, Args... args );templateclassFunction,class... Args std::futuretypenamestd::result_ofFunction(Args...)::typeasync( std::launch policy, Function f, Args... args );其中第二个模板参数是​​启动策略​​std::launch枚举控制任务的执行方式策略说明std::launch::async强制在新线程中异步执行任务类似 std::thread直接启动。std::launch::deferred延迟执行任务不会立即启动直到调用 future.get()或 wait()时才在当前线程同步执行。默认策略无显式指定实现定义通常是 async​​三、基础用法示例​​​​1. 最简用法无显式策略​​1234567templateclassFunction,class... Args std::futuretypenamestd::result_ofFunction(Args...)::typeasync( Function f, Args... args );templateclassFunction,class... Args std::futuretypenamestd::result_ofFunction(Args...)::typeasync( std::launch policy, Function f, Args... args );std::async(compute, 2, 3)启动异步任务传递函数compute和参数2, 3。future.get()阻塞主线程直到任务完成并返回结果。​​2. 显式指定启动策略​​12345678// 强制异步执行新线程auto future_async std::async(std::launch::async, compute, 2, 3);// 延迟执行当前线程同步执行auto future_deferred std::async(std::launch::deferred, compute, 2, 3);future_async.get();// get()阻塞等待future_deferred.get();// 此时在当前线程同步执行 compute(2,3)​​四、参数传递与引用语义​​std::async支持传递任意可调用对象函数、Lambda、函数对象等和参数。若需传递引用需用std::ref包装123456789101112131415161718#include functionalvoidmodify(int value) {value 100;}intmain() {intx 0;// 错误直接传递引用会被复制值语义// auto future std::async(modify, x);// 正确用 std::ref 传递引用auto future std::async(modify, std::ref(x));future.get();std::cout x std::endl;// 输出 100x 被修改return0;}​​五、std::future 的常用接口​​std::async返回的std::future提供以下关键方法方法说明get()阻塞直到任务完成返回结果或抛出任务中的异常只能调用一次。wait()阻塞直到任务完成可多次调用。wait_for(timeout)阻塞最多 timeout时间返回 std::future_statusready/timeout/deferred。wait_until(timepoint)阻塞直到指定时间点。valid()检查 future是否关联有效结果未调用 get()时为 true。share()转换为 std::shared_future允许多个对象共享结果。​​六、异常处理​​异步任务中抛出的异常会被std::future捕获直到调用get()时重新抛出1234567891011121314intrisky_compute(intx) {if(x 0)throwstd::runtime_error(x is negative);returnx * 2;}intmain() {auto future std::async(risky_compute, -1);try{intresult future.get();// 抛出 std::runtime_error}catch(conststd::exception e) {std::cerr Error: e.what() ;// 捕获异常}return0;}​​七、注意事项​​​​生命周期管理​​std::future析构时若任务未完成且未被get()或wait()可能导致程序终止取决于实现。若需共享结果使用std::shared_future。​​线程复用​​std::async不保证任务一定在新线程中执行尤其是deferred策略或编译器优化依赖具体实现。​​性能开销​​相比手动管理std::threadstd::async自动管理线程生命周期但频繁创建小任务可能有额外开销适合中高耗时任务。​​八、典型应用场景​​​​并行计算​​同时执行多个独立任务如图像处理中的多区域计算。​​异步IO​​发起IO操作后异步等待结果避免阻塞主线程。​​任务编排​​结合std::future::wait_for实现超时控制如监控任务是否超时。​​总结​​std::async是 C11 中简化异步编程的核心工具通过std::future提供结果获取和状态查询能力。合理使用其启动策略和异常处理机制可有效提升代码的并发性能和可维护性。