C++11 async

C++11异步 async


一、简介

**std::async()**是一个接受回调(函数或函数对象)作为参数的函数模板,并有可能异步执行它们.

函数原型:

template<class Fn, class... Args>
future<typename result_of<Fn(Args...)>::type> async(launch policy, Fn&& fn, Args&&...args);

函数说明:

std::async返回一个,它存储由执行的函数对象返回的值。

函数期望的参数可以作为函数指针参数后面的参数传递给std::async()。

参数说明:

std::async中的第一个参数是启动策略,它控制std::async的异步行为,我们可以用三种不同的启动策略来创建std::async
·std::launch::async
保证异步行为,即传递函数将在单独的线程中执行
·std::launch::deferred
当其他线程调用get()来访问共享状态时,将调用非异步行为
·std::launch::async | std::launch::deferred
默认行为。有了这个启动策略,它可以异步运行或不运行,这取决于系统的负载,但我们无法控制它。


二、案例
#include <iostream>
#include <future>
#include <string>
#include <windows.h>

using namespace std;
void fun1()
{
	Sleep(500);
	std::cout << "fun1..." << std:: endl;
}

void fun2(int n)
{
	Sleep(100);
	std::cout << "fun2 n:"<<n << std::endl;
}
std::string fun3(const std::string& str)
{
	cout << str << endl;
	return str;
}

void fun5(const string& str)
{
	cout << "hello :"<<str << endl;
}
int main()
{
	auto pfun1 = std::async(fun1);
	auto pfun2 = std::async(fun2,2);
	auto pfun3 = std::async(fun3,"hello async");
	//lambda表达式
	auto pfun4 = std::async([] {
		cout << "pfun4" << endl;
	});
	//绑定函数
	auto pfun5 = std::async(bind(fun5,"bind"));
	//获取返回值
	cout << "pfun3:"<< pfun3.get()<< endl;
	system("pause");
	return 0;
}

想了解学习更多C++后台服务器方面的知识,请关注:
微信公众号:C++后台服务器开发

<think>好的,用户想了解C++async函数的用法和相关问题。首先,我需要回忆一下C++11引入的std::async以及相关的功能。std::async是用来异步执行函数,并返回一个std::future对象,以便在之后获取结果。用户可能需要知道基本用法、参数选项、异常处理以及线程池的关系。 根据用户提供的引用内容,特别是引用[2]提到线程池的实现原理和回调函数的使用,用户可能对async与线程池的配合使用感兴趣。需要说明std::async默认是否使用线程池,或者如何结合两者。 接下来,我需要整理async的常用方法,比如启动策略(std::launch::async和std::launch::deferred),以及如何通过future获取结果。还需要举几个例子,比如计算斐波那契数列或者处理多个任务,这样用户能更直观地理解。 另外,用户可能关心异常处理,因为在异步任务中异常无法直接捕获,必须通过future对象来获取。这部分需要详细说明。 还要注意用户提到的引用[1]中的ROS2节点创建,虽然可能与async没有直接关系,但可能在异步任务处理的应用场景中有联系,比如在ROS2中使用async处理回调,但这里可能需要避免混淆,专注于标准库的async。 需要确保回答结构清晰,分点说明用法、示例、注意事项,并生成相关问题。同时检查是否符合格式要求,比如行内公式用$...$,代码块正确,引用标识正确添加。</think>### C++async函数用法详解 #### 一、基本概念 C++11引入的$std::async$函数用于异步执行任务,返回一个$std::future$对象存储计算结果。其核心特性包括: 1. 支持延迟执行($std::launch::deferred$) 2. 强制异步执行($std::launch::async$) 3. 自动回收线程资源[^2] #### 二、核心用法 ```cpp #include <future> #include <iostream> int add(int a, int b) { return a + b; } int main() { // 启动异步任务 auto future = std::async(std::launch::async, add, 10, 20); // 获取结果(阻塞等待) std::cout << "Result: " << future.get() << std::endl; return 0; } ``` #### 三、启动策略对比 | 策略类型 | 行为特征 | |--------------------------|-----------------------------------| | $std::launch::async$ | 强制创建新线程执行 | | $std::launch::deferred$ | 延迟到调用get()/wait()时同步执行 | #### 四、高级应用场景 1. **并行计算** ```cpp auto future1 = std::async([]{ return compute(1); }); auto future2 = std::async([]{ return compute(2); }); auto result = future1.get() + future2.get(); ``` 2. **异常处理** ```cpp try { auto future = std::async([]{ throw std::runtime_error("error"); }); future.get(); } catch(const std::exception& e) { std::cerr << e.what() << std::endl; } ``` 3. **结合线程池使用** 虽然$std::async$本身不直接管理线程池,但可通过自定义分配器实现类似效果: ```cpp // 使用线程池执行异步任务 auto future = std::async(thread_pool_executor, heavy_task); ``` #### 五、性能注意事项 1. 默认策略可能重用线程(取决于实现) 2. 频繁创建任务应考虑线程池方案 3. 返回值类型必须可拷贝或可移动
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值