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

c++怎么使用std::async和std::future_c++异步任务async与future使用示例

裘德小鎮的故事
发布: 2025-10-14 18:56:01
原创
981人浏览过
std::async和std::future用于异步任务执行与结果获取,前者启动任务并返回future对象,后者通过get()获取结果或异常,支持指定启动策略,并可用于并行处理多个任务。

c++怎么使用std::async和std::future_c++异步任务async与future使用示例

在C++11中,std::asyncstd::future 提供了一种简单的方式来启动异步任务并获取其结果。它们位于 red"><future> 头文件中,是处理并发编程的重要工具

基本概念

std::async 用于启动一个异步任务,可以看作是一个“自动包装的线程”,它会在后台执行某个函数。
std::future 是一个占位符对象,用来在未来某个时间点获取异步操作的结果。

当你调用 std::async,它会返回一个 std::future 对象,你可以通过调用该对象的 get() 方法来获取结果。如果结果还没准备好,get() 会阻塞直到结果可用。

使用示例:基本异步计算

下面是一个简单的例子,演示如何使用 std::async 计算两个大数的和,并通过 std::future 获取结果:

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

#include <iostream>
#include <future>
#include <thread>
<p>int heavy_computation(int a, int b) {
std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟耗时操作
return a + b;
}</p><p>int main() {
// 启动异步任务
std::future<int> future_result = std::async(heavy_computation, 100, 200);</p><pre class='brush:php;toolbar:false;'>std::cout << "正在执行其他操作...\n";

// 获取结果(等待完成)
int result = future_result.get();

std::cout << "计算结果: " << result << "\n";
return 0;
登录后复制

}

指定启动策略

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

  • std::launch::async:强制异步运行(创建新线程)
  • std::launch::deferred:延迟运行,直到调用 get() 或 wait() 时才在当前线程执行

默认情况下,std::async 使用 std::launch::async | std::launch::deferred,表示由系统决定。

芦笋演示
芦笋演示

一键出成片的录屏演示软件,专为制作产品演示、教学课程和使用教程而设计。

芦笋演示 34
查看详情 芦笋演示

如果你想确保任务在新线程中运行:

std::future<int> future_result = std::async(
    std::launch::async, 
    heavy_computation, 100, 200
);
登录后复制

如果你希望延迟执行(用于优化或调试):

std::future<int> future_result = std::async(
    std::launch::deferred, 
    heavy_computation, 100, 200
);
登录后复制

多个异步任务并行处理

你也可以同时启动多个异步任务,然后分别获取结果:

#include <iostream>
#include <future>
#include <vector>
<p>int square(int x) {
std::this_thread::sleep_for(std::chrono::milliseconds(500));
return x * x;
}</p><p>int main() {
std::vector<std::future<int>> futures;</p><pre class='brush:php;toolbar:false;'>for (int i = 1; i <= 5; ++i) {
    futures.push_back(std::async(square, i));
}

for (auto& fut : futures) {
    std::cout << fut.get() << " ";
}
std::cout << "\n";

return 0;
登录后复制

}

输出:
1 4 9 16 25

异常处理

如果异步任务抛出异常,这个异常会被捕获并存储。当你调用 future 的 get() 时,异常会重新抛出。

std::future<void> f = std::async([]{
    throw std::runtime_error("出错了!");
});
<p>try {
f.get();
} catch (const std::exception& e) {
std::cout << "捕获异常: " << e.what() << "\n";
}</p>
登录后复制

注意事项

  • 每个 future 只能调用一次 get(),多次调用会导致未定义行为。
  • 如果不调用 get() 或 wait(),某些实现可能会阻塞在析构函数中(特别是使用 deferred 策略时)。
  • std::async 的资源管理依赖于 future 的生命周期,不要提前销毁 future。

基本上就这些。std::async 和 std::future 非常适合用于简单的异步任务,不需要手动管理线程。对于更复杂的场景(如线程池),可能需要结合 std::promise、std::packaged_task 或直接使用 std::thread。

以上就是c++++怎么使用std::async和std::future_c++异步任务async与future使用示例的详细内容,更多请关注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号