线程的创建方式

1、普通充当线程处理函数创建线程

void print()
{
	cout << "线程处理函数启动" << endl;
}
void test1()
{
	thread t1(print); //创建线程
	t1.join(); //线程汇入主线程
}

2、采用Lambda表达式充当线程处理函数

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

3、带参函数创建线程

3.1、普通参数

void printData(const int num)
{
	cout << "id:" << num << endl;
}
void test3()
{
	int num = 1;
	thread t3(printData, num);
	t3.join();
}

3.2、传引用的函数参数

void printReference(const int& num)
{
	cout << "子线程:" << num << endl;
}
void test4()
{
	int num = 1001;
	thread t4(printReference,ref(num));//传引用时必须采用右值引用,用ref包装
	t4.join();
	cout << "主线程:" << num << endl;
}

注意:传引用时,由于主线程可能早于子线程死亡,所以必须传右值引用,用ref包装

3.3、智能指针当做函数参数

void printPtr(unique_ptr<int> ptr)
{
	cout << "智能指针" <<*ptr.get()<< endl; 
}
void test5()
{
	unique_ptr<int> ptr (new int(100)); //智能指针不能产生拷贝本
	//因为智能指针不能产生拷贝本,所以用move语句移动,移动之后主线程就不能使用了,智能指针变为空
	thread t5(printPtr,move(ptr));
	t5.join();
}

3.4 通过类中的成员函数去创建

        仿函数形式:类名的方式调用

class function {
public:
	void operator()()
	{
		cout << "重载()" << endl;
	}
};
void test6()
{
	function obj;
	thread t6(obj);
	t6.join();

	//匿名对象调用重载函数
	thread t7((function()));
	t7.join();


}

 

普通类中的成员函数

class MM {
public:
	void print(int& id)
	{
		cout << "id:" << id << endl;
	}
protected:
};

void test8()
{
	MM mm;
	int id = 19;
	thread t8(&MM::print, mm, ref(id));//右值引用
	t8.join();

}

测试:

int main()
{
	test1();
	test2();
	test3();
	test4();
	test5();
	test6();
	test8();
	return 0;
}

 

谢谢大家

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值