C++多线程学习(二、多线程的几种创造方式【有返回值的之后讲】)

目录

创建多线程

1.普通函数充当线程处理函数创造线程

2.Lambda表达式充当线程处理函数

3.带参函数创建线程

3.1普通参数

3.2传入引用

3.3智能指针充当函数参数

4.通过类中的成员函数创建

4.1仿函数方式创建:类名的方式调用

4.2普通类中的成员函数


创建多线程

1.普通函数充当线程处理函数创造线程

#include <thread>
#include <iostream>
using namespace std;
void ThreadPrint()
{
	cout << "线程启动" << endl;
}
void ThreadOpen()
{
	thread t1(ThreadPrint);//无输入无返回值的函数
	t1.join();
}
int main()
{
	ThreadOpen();


	return 0;
}

2.Lambda表达式充当线程处理函数

#include <thread>
#include <iostream>
using namespace std;

void ThreadLambda()
{
	thread t1([]() {cout << "Lambda表达式充当线程处理函数" << endl; });
	t1.join();
}
int main()
{
	

	ThreadLambda();
	return 0;
}

3.带参函数创建线程

3.1普通参数

#include <thread>
#include <iostream>
using namespace std;

void WhatYourYear(int num)//const int num 也是可以的
{
	cout << "your year:" << num << endl;
}
void ThreadHaveInt(int Pnum)//创建带参数的普通线程,你需要有这个数
{
	int num = 1;
	thread t1(WhatYourYear, num);
	t1.join();
	thread t2(WhatYourYear, Pnum);
	t2.join();
}
int main()
{
	ThreadHaveInt(9);

	
	return 0;
}

3.2传入引用

#include <thread>
#include <iostream>
using namespace std;

void IntoRef(int& num)//如果加上const,把 num=1001删除
{
	num = 1001;
	cout << "子线程" << num << endl;
}
void ThreadHaveRef()
{
	int num = 0;
	thread t1(IntoRef, ref(num));//这里thread后面传入的为&&,所以对num要包装引用作为传递的值
	t1.join();
	cout << "主线程" << num << endl;
}
int main()
{
	ThreadHaveRef();

	
	return 0;
}

3.3智能指针充当函数参数

因为智能指针是不能被复制的,而是具有所有权的资源管理对象,因此不能直接传递给子线程的函数。

所以通过使用move函数,来将智能指针ptr从主线程移动到新的子线程中,将ptr的所有权转移到子线程中,以便在子线程中正确访问智能指针的资源,可以实现将智能指针的所有权从一个上下文转移到另一个上下文。

#include <thread>
#include <iostream>
using namespace std;

void printPtr(unique_ptr<int> ptr)
{
	cout << "智能指针" << ptr.get()<< endl;
}
void ThreadSmartPtr()
{
	unique_ptr<int> ptr(new int(100));
	cout << "主线程打印:" << ptr.get() << endl;
	thread t1(printPtr, move(ptr));//move语句作为处理
	t1.join();
	cout << "转移后的主线程打印:" << ptr.get() << endl;//是空的
}
int main()
{
	ThreadSmartPtr();

	
	return 0;
}

4.通过类中的成员函数创建

4.1仿函数方式创建:类名的方式调用

#include <thread>
#include <iostream>
using namespace std;

class TestFunction
{
public:
	void operator()()
	{
		cout << "重载()" << endl;
	}
};
void ThreadOperator()
{
	TestFunction TF1;//直接通过类创建对象,将对象传入线程
	thread t1(TF1);//这样就会调用一下void operator()()
	t1.join();
	//匿名对象
	thread t2((TestFunction()));//多加一个()帮助进行解析
	t2.join();
}
int main()
{
	ThreadOperator();

	
	return 0;
}


4.2普通类中的成员函数

#include <thread>
#include <iostream>
using namespace std;

class LH
{
public:
	void print(int& num)//自己选择用什么模式的函数
	{
		cout << "people:" << num << endl;
	}
};
void ThreadClassOne()
{
	LH a;//指定对象
	int num = 1;
	thread t1(&LH::print, a, ref(num));//哪个类的函数,哪个对象,传入的值
	t1.join();
}
int main()
{
	
	ThreadClassOne();
	
	return 0;
}


猜你喜欢

转载自blog.csdn.net/q244645787/article/details/131525118