C++11多线程(2)

多线程的创建方法:
一、函数指针形式

将线程函数的函数名(函数指针)作为线程对象的参数进行创建线程,如果线程函数有参数,将参数按顺序传入线程对象,如下所示:

#include <iostream>
#include <thread>		  //1

using namespace std;
//2
void SonThread(int a, int b)
{
	cout << "子线程开始" << endl;
	cout << a + b << endl;
	cout << "子线程退出"<<endl;
}

int main()
{
	thread demo(SonThread, 3, 4); //3
	demo.join();			//4
	cout << "主线程运行结束" << endl;
	system("Pause");
	return 0;
}

二、类对象作为参数进行创建多线程

类对象可以作为cans参数创建多线程,必须显示标注对象属于哪一个类,首先将需要的类的函数名传入,对象名,函数参数

形式如下:thread test(&类名::函数名,&对象名,参数......);

#include <iostream>
#include <thread>

using namespace std;

class CThread
{
public:
	void showThread(int a, int b)
	{
		cout << "子线程开始" << endl;
		cout << a + b << endl;
		cout << "子线程结束" << endl;
	}
};

int main()
{
	cout << "主线程开始" << endl;
	CThread a;
	thread demo(&CThread::showThread, &a, 3, 4);
	demo.join();
	cout << "主线程结束" << endl;
	system("Pause");
	return 0;
}

三、lamda函数

#include <iostream>
#include <thread>

using namespace std;

int main()
{
	thread t([]()
	{
		cout << "thread function\n";
	});
	cout << "main thread\n";
	t.join();
	system("Pause");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/u012967763/article/details/82834899