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

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

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

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

基本用法:启动异步任务

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

 #include <iostream> #include <future> #include <chrono> <p>int longRunningTask() { std::this_thread::sleep_for(std::chrono::seconds(2)); return 42; }</p><p>int main() { // 启动异步任务 std::future<int> result = std::async(longRunningTask);</p><pre class='brush:php;toolbar:false;'>// 执行其他操作... std::cout << "Doing other work...n";  // 获取结果(阻塞直到完成) int value = result.get(); std::cout << "Result: " << value << "n"; return 0;

}

指定启动策略

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

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

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

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

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

AppMall应用商店

AI应用商店,提供即时交付、按需付费的人工智能应用服务

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

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

 // 明确要求异步执行 auto future1 = std::async(std::launch::async, longRunningTask); <p>// 明确延迟执行(不会创建线程,只在 get 时运行) auto future2 = std::async(std::launch::deferred, longRunningTask);</p>

如果选择 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; }; <p>auto future = std::async(taskWithParams, "Alice", 3); // ... int res = future.get();</p>

异常处理

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

 auto faultyTask = []() -> int {     throw std::runtime_error("Something went wrong!"); }; <p>auto fut = std::async(faultyTask); try { fut.get(); } catch (const std::exception& e) { std::cout << "Caught exception: " << e.what() << "n"; }</p>

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

上一篇
下一篇
text=ZqhQzanResources