C++线程学习2,成员函数、lambda临时函数作为线程入口并封装线程基类接口

本文介绍了C++中线程接口的基本使用方法,包括通过成员函数启动线程、封装线程基类接口以及使用lambda表达式作为线程入口。演示了不同场景下线程创建与管理的具体实现。

1,基本的接口调用

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

class MyThread
{
public:
	void threadMain()
	{
		//this_thread::sleep_for(5ms);
		cout << "threadMain   name = " << this->name << endl;
	}
public:
	//C++11 可以设定默认值
	string name = "小青";
};

int main()
{
	MyThread thread1;
	thread1.name = "test——1";
	thread th1 = thread(&MyThread::threadMain, &thread1);
	th1.join();
	getchar();
	
	return 0;
}

成员函数做线程的入口时,传参时候 成员函数的地址+ 对象的地址(this指针)。

封装线程基类接口

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

//线程基类
class BaseThread 
{
public:
	virtual void Start()
	{
		cout << "BaseThread_Start" << endl;
		this->is_exit_ = false;
		_th = thread(&BaseThread::Func,this);
	}

	virtual void Wait()
	{
		if (_th.joinable())
		{
			_th.join();
		}
	}

	virtual void Stop()
	{
		this->is_exit_ = true;
		Wait();
	}

	bool is_exit()
	{
		return is_exit_;
	}
private:
	bool is_exit_ = false;
	std::thread _th;

	virtual void Func() = 0;//设计成纯虚函数时,派生类必须实现
};

class TestThread :public BaseThread
{
public:
	void Func()override
	{
		cout << "TestThread func" << endl;
		cout << "test_data  =  " << this->test_data << endl;

		while (!is_exit())
		{
			this_thread::sleep_for(100ms);
			cout << "." << flush;//刷新打印显示
		}
		cout << "线程退出,,,,,,,," << endl;
	}

public:
	string test_data;

};

int main()
{
	TestThread thread1;
	thread1.test_data = "test——1";
	thread1.Start();
	getchar();		//收到键盘动作后 Stop
	thread1.Stop();//线程退出

	thread1.Wait();
	return 0;
}

3,lambda临时函数作为线程入口

lambda函数格式:
[捕捉列表](参数)mutable-> 返回值类型 (函数体)

线程实例:
//带传递参数的
int main()
{
	thread t([](int data) {
		cout << "t = " << data << endl;
		}, 1000
	);
	t.join();
		return 0;
}
成员函数中使用lambda表达式做线程入口:
class LambdaTest
{
public:
	void Starat()
	{
		thread t([this]() {cout << "Lambda testData = " << testData << endl; });
		t.join();
	}

public:
	string testData;
};
int main()
{
	LambdaTest test1;
	test1.testData = "测试中,,,,,,,";
	test1.Starat();

	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值