std::async 提供便捷的异步任务启动方式,返回 future 获取结果,支持 async 和 deferred 执行策略,可管理多个任务并处理异常。

在C++11中引入的 std::async 是进行异步编程的一种便捷方式,它允许你以简单的方式启动一个异步任务,并通过 std::future 获取其返回结果。相比直接使用线程(std::thread),std::async 更加灵活,能自动管理线程生命周期,并支持延迟执行策略。
std::async 是一个函数模板,用于启动一个异步任务。它返回一个 std::future 对象,该对象可用于获取异步操作的结果。
示例代码:<pre class="brush:php;toolbar:false;">#include <iostream><br>#include <future><br>#include <thread><br><br>int long_computation() {<br> std::this_thread::sleep_for(std::chrono::seconds(2));<br> return 42;<br>}<br><br>int main() {<br> // 启动异步任务<br> std::future<int> result = std::async(long_computation);<br><br> std::cout << "正在执行其他工作...\n";<br><br> // 获取结果(会阻塞直到完成)<br> int value = result.get();<br> std::cout << "异步结果: " << value << "\n";<br><br> return 0;<br>}在这个例子中,long_computation 在后台执行,主线程可以继续做其他事情,直到调用 get() 时才等待结果。
立即学习“C++免费学习笔记(深入)”;
std::async 支持两种执行策略:
也可以使用按位或组合两者,让系统自行决定:
指定执行策略示例:<pre class="brush:php;toolbar:false;">// 强制异步执行<br>auto future1 = std::async(std::launch::async, long_computation);<br><br>// 延迟执行<br>auto future2 = std::async(std::launch::deferred, long_computation);<br><br>// 让系统决定<br>auto future3 = std::async(std::launch::async | std::launch::deferred, long_computation);
注意:如果使用 deferred 策略,任务不会立即运行,而是在调用 get() 时同步执行。
实际开发中常需并发处理多个任务。可以通过容器保存多个 std::future 来统一管理。
批量启动异步任务:<pre class="brush:php;toolbar:false;">#include <vector><br>#include <future><br><br>std::vector<std::future<int>> tasks;<br><br>for (int i = 0; i < 5; ++i) {<br> tasks.push_back(std::async([i] {<br> std::this_thread::sleep_for(std::chrono::milliseconds(100 * (i + 1)));<br> return i * i;<br> }));<br>}<br><br>// 收集结果<br>for (auto& task : tasks) {<br> std::cout << "结果: " << task.get() << "\n";<br>}每个任务独立运行,get() 调用会按顺序阻塞,直到对应任务完成。若想实现更高效的等待(如任一完成就处理),可结合 std::future_status 和 wait_for 实现轮询。
异步任务中抛出的异常会被捕获并存储,当调用 get() 时重新抛出。
<pre class="brush:php;toolbar:false;">auto faulty_task = std::async([] {<br> throw std::runtime_error("出错了!");<br>});<br><br>try {<br> faulty_task.get();<br>} catch (const std::exception& e) {<br> std::cout << "捕获异常: " << e.what() << "\n";<br>}确保始终调用 get() 或 wait(),否则在析构时若任务是异步执行的,程序可能阻塞等待任务结束(仅对 std::launch::async 情况)。
基本上就这些。合理使用 std::async 可简化异步逻辑,避免手动管理线程,但要注意执行策略的选择和 future 的及时获取,防止意外阻塞或资源泄漏。
以上就是c++++中如何使用std::async进行异步编程_std::async异步任务创建与管理的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号