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

在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),由系统决定。
// 明确要求异步执行 auto future1 = std::async(std::launch::async, longRunningTask); <p>// 明确延迟执行(不会创建线程,只在 get 时运行) auto future2 = std::async(std::launch::deferred, longRunningTask);</p>
如果选择 async 策略但系统无法创建线程,会抛出异常。
可以向 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++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号