首页 > 后端开发 > C++ > 正文

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

裘德小鎮的故事
发布: 2025-11-04 22:17:02
原创
650人浏览过
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),由系统决定。

AppMall应用商店
AppMall应用商店

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

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

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

c++速学教程(入门到精通)
c++速学教程(入门到精通)

c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号