C++的std::async怎么异步执行函数_C++ async异步任务执行方法详解

std::async 提供异步执行函数并获取结果的简便方式,返回 future 对象。支持 async(新线程立即执行)和 deferred(延迟同步执行)策略,默认策略由系统决定。可执行函数或 Lambda,异常会被捕获并在 get 时抛出。相比 std::Thread,std::async 更易管理返回值和生命周期,适合需要结果获取的并发任务。

C++的std::async怎么异步执行函数_C++ async异步任务执行方法详解

c++11中,std::async 提供了一种简洁的方式来异步执行函数或可调用对象,从而实现多线程任务的并行处理。它封装了线程创建和结果获取的复杂性,返回一个 std::future 对象,用于在将来获取函数的执行结果。

std::async 基本用法

std::async 定义在头文件 <future> 中,其基本语法如下:

std::future<T> result = std::async(launch_policy, function, args…);

其中:

  • launch_policy:指定启动策略,可选 std::launch::asyncstd::launch::deferred
  • function:要异步执行的函数、lambda表达式或仿函数
  • args…:传递给函数的参数
  • 返回值是 std::future,用于获取函数返回值或异常

例如,异步计算两个数的和:

立即学习C++免费学习笔记(深入)”;

#include <future>
#include <iostream>

int add(int a, int b) {
return a + b;
}

int main() {
auto future_result = std::async(std::launch::async, add, 2, 3);
std::cout << “Result: ” << future_result.get() << std::endl;
return 0;
}

启动策略详解

std::async 支持两种启动策略,控制任务的执行方式:

std::launch::async

C++的std::async怎么异步执行函数_C++ async异步任务执行方法详解

行者AI

行者ai绘图创作,唤醒新的灵感,创造更多可能

C++的std::async怎么异步执行函数_C++ async异步任务执行方法详解100

查看详情 C++的std::async怎么异步执行函数_C++ async异步任务执行方法详解

  • 强制在新线程中立即执行函数
  • 真正实现“异步”并发
  • 若系统无法创建线程,会抛出 std::system_error

std::launch::deferred

  • 延迟执行,函数不会立即运行
  • 只有当调用 future.get()wait() 时才在当前线程同步执行
  • 不创建新线程,适合轻量级或可能不需要执行的任务

如果不指定策略,如:
std::async(add, 2, 3);
编译器可自行选择 async 或 deferred,行为不确定,建议明确指定策略。

异步执行 Lambda 表达式

除了普通函数,也可以异步执行 lambda:

auto task = std::async(std::launch::async, [](int x) {
// 模拟耗时操作
std::this_thread::sleep_for(std::chrono::seconds(2));
return x * x;
}, 5);

std::cout << “Square: ” << task.get() << std::endl;

这段代码在后台线程中计算 5 的平方,主线程可以等待结果。

异常处理机制

如果异步函数抛出异常,该异常会被捕获并存储在 future 中。调用 get() 时会重新抛出:

auto faulty = std::async(std::launch::async, [](){
throw std::runtime_error(“Something went wrong!”);
});

try {
faulty.get();
} catch (const std::exception& e) {
std::cout << “Caught exception: ” << e.what() << std::endl;
}

这保证了异常安全,避免未捕获异常导致程序终止。

与 std::thread 的区别

  • std::async 返回 std::future,便于获取返回值;std::thread 不直接支持返回值
  • std::async 可自动管理线程生命周期std::thread 需手动调用 join 或 detach
  • std::async 支持延迟执行策略;std::thread 总是立即启动
  • 对于简单任务,std::async 更简洁安全

基本上就这些。std::async 是 C++ 中实现异步任务最直观的方式之一,尤其适合需要获取结果的场景。合理使用 launch 策略,能更好控制执行时机和资源消耗。虽然某些高性能场景下可能倾向直接使用线程池或 std::packaged_task,但 std::async 依然是入门和日常开发的首选。

上一篇
下一篇
text=ZqhQzanResources