C++多线程高并发,async,以及参数std::launch::deferred , std::launch::async

async
就是设计模式里面的“未来模式”,不能立即得到结果,

async:启动一个异步任务
意思就是:自动创建一个线程,执行线程的入口函数,返回一个std::future对象 std::future可以得到线程入口函数的返回结果,使用方法get()即可 但是get函数只能调用一次,不能调用多次
使用方法如下:

int threadStepInMethod()
{
	std::cout << "thread start " << std::endl;
	std::cout << "线程id:" << std::this_thread::get_id() << std::endl;
	std::chrono::milliseconds dura(5000);
	std::this_thread::sleep_for(dura);
	std::cout << " thread end " << std::endl;
	return 666;
}

int main()
{
	myClassA a;
	int param1 = 3;
	std::cout << "main thread id = " << std::this_thread::get_id() << std::endl;
	std::future<int> result = std::async(threadStepInMethod);
	std::cout << "main thread can do ather things , but if you want to get the future answer , you"
		<<"must wait unit it finished its work "<<std::endl;

	//即使不使用std::future.get()方法获取返回值,主线程依然会等待子线程结束之后再销毁
	std::cout << " the answer is : " << result.get() << std::endl;
	std::cout << " continue" <<  std::endl;
}

如果传入第二个参数,std::launch::deferred,那么线程的执行就会推迟到std::future.get()方法时才会启动 如果不使用get或者wait时,线程直接结束,不会执行线程入口函数内的东西 如果使用的话,也会发现,根本没有创建新的线程,就是再主线程中调用的线程入口函数

如果第二个参数传入的书:std::launch::async,那么就是声明的时候就回去创建新的线程
系统默认使用的就是这个参数

如下所示:(使用类的成员函数作为线程的入口函数)

class myClassA
{
public:
	int threadStepInMethod2(int param1)
	{
		std::cout << "thread start " << std::endl;
		std::cout << "线程id:" << std::this_thread::get_id() << std::endl;
		std::chrono::milliseconds dura(5000);
		std::this_thread::sleep_for(dura);
		std::cout << " thread end " << std::endl;
		return param1 * 100;
	}
};

int main()
{
	myClassA a;
	int param1 = 3;


	std::cout << "main thread id = " << std::this_thread::get_id() << std::endl;
	//第一种,使用残数为std::launch::deferred
	//std::future<int> result = std::async(std::launch::deferred,&myClassA::threadStepInMethod2 , &a , param1);
	//第二种,使用参数std::launch::async,就和没使用是一模一样的
	//原因就是默认使用这个参数
	std::future<int> result = std::async(std::launch::async,&myClassA::threadStepInMethod2 , &a , param1);
	std::cout << "main thread can do ather things , but if you want to get the future answer , you"
		<<"must wait unit it finished its work "<<std::endl;

	//即使不使用std::future.get()方法获取返回值,主线程依然会等待子线程结束之后再销毁
	std::cout << " the answer is : " << result.get() << std::endl;
	std::cout << " continue" <<  std::endl;
}
  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值