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 #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 << "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),由系统决定。

// 明确要求异步执行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 可简化异步编程,避免手动管理线程,同时获得返回值和异常支持。

以上就是c++++怎么使用std::async实现异步任务_c++ std::async异步任务执行方法的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1482529.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年12月19日 06:27:23
下一篇 2025年12月19日 06:27:35

相关推荐

发表回复

登录后才能评论
关注微信