std::async是C++中用于简化异步任务执行的工具,通过返回std::future获取结果,支持std::launch::async(新线程执行)和std::launch::deferred(延迟执行)两种策略,默认由系统决定;可传递函数参数或使用lambda表达式,并能捕获异常以保证安全。

在C++中,std::async 是实现异步调用的重要工具之一,它允许你以简单的方式启动一个任务并在后台执行,而无需手动管理线程。通过 std::async,你可以方便地获取任务的返回值,并控制任务的执行策略。
std::async 是定义在 <future> 头文件中的模板函数,用于异步执行一个可调用对象(如函数、lambda表达式或函数对象)。它返回一个 std::future 对象,用来获取异步任务的结果。
示例:
#include <future>
#include <iostream>
<p>int compute() {
return 42;
}</p><p>int main() {
auto future = std::async(compute);
int result = future.get(); // 阻塞等待结果
std::cout << "Result: " << result << std::endl;
return 0;
}</p>在这个例子中,compute() 函数在后台执行,调用 future.get() 时主线程会等待直到结果可用。
立即学习“C++免费学习笔记(深入)”;
std::async 支持两种执行策略:
你可以显式指定策略:
auto future1 = std::async(std::launch::async, compute); // 异步执行 auto future2 = std::async(std::launch::deferred, compute); // 延迟执行 auto future3 = std::async(std::launch::async | std::launch::deferred, compute); // 让系统决定
如果不指定,默认行为由系统决定,可能是异步也可能是延迟执行。
你可以向 std::async 传递参数,就像调用普通函数一样:
int add(int a, int b) {
return a + b;
}
<p>auto future = std::async(add, 5, 3);
std::cout << "Sum: " << future.get() << std::endl;</p>也可以使用 lambda 表达式封装更复杂的逻辑:
auto future = std::async([](int x) {
return x * x;
}, 10);
<p>std::cout << "Square: " << future.get() << std::endl;</p>如果异步任务抛出异常,该异常会被捕获并存储在 future 中。当你调用 get() 时,异常会被重新抛出。
auto future = std::async([] {
throw std::runtime_error("Something went wrong");
});
<p>try {
future.get();
} catch (const std::exception& e) {
std::cout << "Caught exception: " << e.what() << std::endl;
}</p>务必使用 try-catch 捕获可能的异常,避免程序崩溃。
基本上就这些。std::async 提供了简洁的方式来执行并发任务,适合大多数需要异步计算的场景。不复杂但容易忽略的是执行策略的选择和异常的安全处理。合理使用 future 和 async,能显著提升程序响应性和资源利用率。
以上就是c++++如何使用std::async实现异步调用_C++并发任务的异步执行方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号