c++怎么使用std::async实现异步任务_c++ std::async异步任务执行方法

std::async 是 C++11 提供的异步任务启动工具,通过返回 std::future 对象获取结果,支持 std::launch::async(立即创建线程)和 std::launch::deferred(延迟执行)两种策略,可传递参数或使用 lambda,并能捕获和传播异常,简化了线程管理和异步编程。

在C++11中,std::async 是一个用于启动异步任务的便捷工具,它能自动管理线程生命周期,并通过 std::future 获取任务返回结果。相比直接使用 std::thread,它更安全、更灵活,适合执行有返回值的耗时操作。

基本用法:启动异步任务

调用 std::async 会启动一个异步任务,返回一个 std::future 对象,用于后续获取结果。

#include 
#include 
#include 

int longRunningTask() { std::this_thread::sleep_for(std::chrono::seconds(2)); return 42; }

int main() { // 启动异步任务 std::future result = std::async(longRunningTask);

// 执行其他操作...
std::cout zuojiankuohaophpcnzuojiankuohaophpcn "Doing other work...\n";

// 获取结果(阻塞直到完成)
int value = result.get();
std::cout zuojiankuohaophpcnzuojiankuohaophpcn "Result: " zuojiankuohaophpcnzuojiankuohaophpcn value zuojiankuohaophpcnzuojiankuohaophpcn "\n";
return 0;

}

指定启动策略

std::async 支持两种启动策略:

  • std::launch::async:强制创建新线程立即执行
  • std::launch::deferred:延迟执行,直到调用 get()wait()

默认行为是两者皆可(std::launch::async | std::launch::deferred),由系统决定。

// 明确要求异步执行
auto future1 = std::async(std::launch::async, longRunningTask);

// 明确延迟执行(不会创建线程,只在 get 时运行) auto future2 = std::async(std::launch::deferred, longRunningTask);

如果选择 async 策略但系统无法创建线程,会抛出异常。

传递参数和使用 lambda

可以向 std::async 传递参数,包括 lambda 表达式。

auto taskWithParams = [](const std::string& name, int count) {
    for (int i = 0; i < count; ++i) {
        std::cout << "Hello, " << name << "\n";
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
    return count * 10;
};

auto future = std::async(taskWithParams, "Alice", 3); // ... int res = future.get();

异常处理

异步任务中抛出的异常会被捕获并存储,调用 get() 时重新抛出。

auto faultyTask = []() -> int {
    throw std::runtime_error("Something went wrong!");
};

auto fut = std::async(faultyTask); try { fut.get(); } catch (const std::exception& e) { std::cout << "Caught exception: " << e.what() << "\n"; }

基本上就这些。合理使用 std::async 可简化异步编程,避免手动管理线程,同时获得返回值和异常支持。