c++中的async

 在c++11中为我们提供了一种十分简易又遍历的异步线程的方法,这种就是async。以下是async的一些使用方法。分为以下几步:如何启动异步线程,如何知道异步线程的状态,怎么得到异步线程的结果。async的头文件时future.

#include "future"
#include "thread"
#include "iostream"
#include "windows.h"
using namespace std;

class A
{
public:
	A() {}
	void print(int a) { cout << a << endl; }
};
int main()
{
	A a;
	//std::future 的三种启动策略
	//1.std::launch::deferred 当其他线程调用get来获取状态时,将调用非异步行为 
	//2.std::launch::async 保持异步行为,即传入的线程函数将在另一个线程中异步执行
	//3.std::launch::deferred | std::launch::async,默认启动策略,他可以异步或着同步执行,取决与系统,不能自己控制
	//推荐每次使用async时,都使用std::launch::async
	//代码一
	//std::future<int> result = async(std::launch::async, [&a](int i) {Sleep(10000); cout << i << endl; return i + 1; }, 5);
	//std::future<int> result = async(std::launch::async, [&a](int i) {Sleep(10000); a.print(i); return i + 1; }, 5);
	//cout << "hello" << endl;
	//Sleep(10000);
	//cout << "result" << result.get() << endl;

	//std::future 获取状态的三种方式
	//1.get 等待异步操作结束并返回结果,get只能调用一次,因为会使future失效,会启动没启动的线程
	//2.wait 只是等待异步操作完成,没有返回值,会启动没启动的线程
	//3.wait_for 超时等待返回结果。,不会启动没启动的线程
	//所以需要得到返回结果的时候,只能使用get

	//std::future 的三种状态
	//1.std::future_status::deferred 异步操作还没开始
	//2.std::future_status::ready 异步操作已经完成 
	//3.std::future_status::timeout 异步操作超时

	//std::future<int> result = async(std::launch::async, [&a](int i) {Sleep(10000); a.print(i); return i + 1; }, 5);
	//cout << "hello" << endl;
	//std::future_status status;
	//do
	//{
	//	status = result.wait_for(std::chrono::seconds(1));
	//	if (std::future_status::deferred == status)
	//	{
	//		cout << "线程还未启动" << endl;
	//	}
	//	else if (std::future_status::ready == status)
	//	{
	//		cout << "线程已启动" << endl;
	//	}
	//	else
	//	{

	//		cout << "线程超时" << endl;
	//	}
	//} while (std::future_status::ready != status);

	//async获取线程结果的三种途径
	//1.使用std::future ,通过get获取到返回的结果
	//2.std::promise std::promise为获取线程函数中的某个值提供便利,
		//在线程函数中给外面传进来的promise赋值,通过get_future获取的结果
	//注意的是取值是间接的通过promise内部提供的future来获取的
	//3.std::packaged_taskstd::packaged_task它包装了一个可调用的目标
		//(如function, lambda expression, bind expression, or another function object)
		//,以便异步调用,它和promise在某种程度上有点像,promise保存了一个共享状态的值,
		//而packaged_task保存的是一个函数
	//代码三

	std::promise<int> pr;
	async(std::launch::async, [](std::promise<int>& p) {p.set_value(10);}, std::ref(pr));
	std::future<int> param = pr.get_future();
	cout << "value is " << param.get() << endl;

	std::packaged_task<int()> task([]() {return 8; });
	async(std::launch::async, std::ref(task));
	std::future<int> param2 = task.get_future();
	cout << "task value is " << param2.get() << endl;

	
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值