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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_40666620/article/details/102639505

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;
}

猜你喜欢

转载自blog.csdn.net/qq_40666620/article/details/102639505