🔥个人主页🔥:孤寂大仙V
🌈收录专栏🌈:Linux
🌹往期回顾🌹:【Linux笔记】——Linux线程控制创建、终止与等待|动态库与内核联动
🔖流水不争,争的是滔滔不息
一、线程封装简介
在Linux环境下,线程操作是并发编程的核心之一。为了简化线程的创建、管理以及资源回收,实现了一个基于pthread库(原生线程库)的线程封装类。该封装类提供了线程的创建、启动、终止、分离和回收等功能,极大的简化了多线程编程的复杂性。
核心功能
- 线程的创建与启动
通过Start()方法创建并启动线程,线程的执行函数通过包装器function<void()>类型传入,提供了灵活的函数调用方式。 - 线程终止
Stop方法用于终止正在运行的线程,确保线程资源的及时释放。 - 线程分离
Detach方法将线程设置为分离状态,分离后的线程在终止时会自动释放资源,无需显示的回收。 - 线程回收
join方法用于等待线程结束并回收其资源,适用于未分离的线程。
都是使用pthread库内函数实现简单封装这个线程类。
二、线程封装源码
#ifndef _THREAD_HPP_
#define _THREAD_HPP_
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <functional>
#include <pthread.h>
using namespace std;
namespace Threaddemo
{
static uint32_t number=1;
class Thread
{
using func_t=function<void()>;
public:
Thread(func_t func)
:_tid(0)
,_isrunning(false)
,_isdetach(false)
,_func(func)
{
_name="thread-"+to_string(number++);
}
void EnableRunning()
{
_isrunning=true;
}
void EnableDetach()
{
_isdetach=true;
}
static void* routine(void* args)
{
Thread* self=static_cast<Thread*>(args);
self->EnableRunning();
if (self->_isdetach)
self->Detach();
pthread_setname_np(self->_tid, self->_name.c_str());
self->_func();
return nullptr;
}
bool Start()
{
if(_isrunning)
return false;
int n=pthread_create(&_tid,nullptr,routine,this);//
if(n!=0)
{
cerr<<"线程创建出现错误"<<strerror(n)<<endl;
return false;
}
else
{
cout<<"线程创建成功"<<endl;
return true;
}
}
bool Stop() //终止线程
{
if(_isrunning)
{
int n=pthread_cancel(_tid);
if(n!=0)
{
cerr<<"线程终止失败"<<strerror(n)<<endl;
return false;
}
else
{
cout<<"线程终止"<<endl;
return true;
}
}
return false;
}
void Detach() //分离线程
{
if(_isdetach)
return;
if(_isrunning)
{
pthread_detach(_tid);
}
EnableDetach();
}
void Join() //回收线程
{
if(_isdetach)
{
cout<<"已经分离,不能回收"<<endl;
}
int n=pthread_join(_tid,nullptr);
if(n!=0)
{
cerr<<"线程回收失败"<<strerror(n)<<endl;
}
else
{
cout<<"线程回收成功"<<endl;
}
}
~Thread(){}
private:
pthread_t _tid;
bool _isrunning;
bool _isdetach;
string _name;
func_t _func;
};
}
#endif
三、线程封装类
Thread类,私有成员线程id,判断用的_isrunning判断线程是否启动,_isdetach判断线程是否分离。_name构造这个类的时候搞个字符串记录一下,标识。_func是函数指针类型的对象,变量 _func 可以存储任何符合 func_t 签名的函数指针,用来作为回调函数传入,比如线程启动函数、任务执行函数等(这个玩意非常好用,分层很好使)。
Thread(func_t func)
: _tid(0)
, _isrunning(false)
, _isdetach(false)
, _func(func)
{
_name = "thread-" + to_string(number++);
}
构造这个线程类
线程创建与启动
static void *routine(void *args)
{
Thread *self = static_cast<Thread *>(args);
self->EnableRunning();
if (self->_isdetach)
self->Detach();
pthread_setname_np(self->_tid, self->_name.c_str());
self->_func();
return nullptr;
}
bool Start() // 线程创建与启动
{
if (_isrunning)
return false;
int n = pthread_create(&_tid, nullptr, routine, this); //
if (n != 0)
{
cerr << "线程创建出现错误" << strerror(n) << endl;
return false;
}
else
{
cout << "线程创建成功" << endl;
return true;
}
}
这里是创建线程的经典操作,但是我们发现这个void *routine前面怎么加了个static啊成了静态函数了,pthred_create函数最后一个参数最后怎么是this指针啊?
我们知道要想调用类内普通成员函数,必须通过对象调用这个成员函数,加了static的成员函数不依赖于类的对象,也就不需要this指针。这个routine底层是Thread::routine(Thread* this,void* arg)
,也就是说这个函数多一个默认的this指针参数,和pthread_create()要求的额(void* ->void*)完全不匹配,编译报错或强转后出bug。
所以加static,让它成为静态成员函数不依赖于this指针,可以当作函数指针传入pthread_create,抹油默认参数,就不会报错了。妙就妙在在pthread_create中第四个参数传入this,然后传入routine()中再传回去,这样routine就又拿到了对象指针。然后就可以继续访问对象的成员函数了。
加 static 是为了匹配 pthread 的函数指针要求,传 this 是为了绕回来访问类的成员。
在static void *routine(void *args)
函数中, self->_func();
构造的时候func_t是一个函数指针类型的别名,定义为std::function<void()>
表示一个返回类型为void,无参数的函数类型。这就是一个回调函数,说白了就是任务在上层执行完然后把返回值返回来。
_func 是一个函数对象,用来存储线程要执行的任务代码。routine() 中调用它,就等于“开始执行这个线程的工作”,这也是为什么 std::function<void()> 是多线程封装中最常用的任务抽象。
顺便聊一下这里的lambda表达式
Thread t([](){
int cnt=5;
while(cnt--)
{
cout<<"我是一个新线程"<<endl;
}
});
这是这个线程封装的lambda表达式,比较简单,没有捕捉对象和传参,因为function中是void类型。下面我搞个别的lambda表达式在这里聊一下语法。
// 3. 服务器层
unique_ptr<Tcpserver> tsvr = make_unique<Tcpserver>(port,
[&protocol](shared_ptr<Socket> &sock, InetAddr &client){
protocol->GetRequest(sock, client);
});
这里unique_ptr和make_unique都是智能指针的一套流程,通过指针来实例对象。这里是创建服务器,是服务器类也就是类型,port是参数,前面的不过多赘述了,以后会聊。[]里面的是对对象进行捕捉,()里的内容是写_func 函数对象时写的参数,{}里就是要去干的活了,也是为什么要捕捉对象GetRequest是protocol对象类内的成=函数。
线程终止
bool Stop() // 终止线程
{
if (_isrunning)
{
int n = pthread_cancel(_tid);
if (n != 0)
{
cerr << "线程终止失败" << strerror(n) << endl;
return false;
}
else
{
cout << "线程终止" << endl;
return true;
}
}
return false;
}
这个没什么好说的了,就是终止线程,调pthread库内的pthread_cancel函数就完事了。线程必须是运行着的才能终止。
线程分离
void Detach() // 分离线程
{
if (_isdetach)
return;
if (_isrunning)
{
pthread_detach(_tid);
}
EnableDetach();
}
这也没什么好说的,也是pthread库的调用,如果已经分离了返回,如果正在运行分离,分离完标记一下。
线程回收
void Join() // 回收线程
{
if (_isdetach)
{
cout << "已经分离,不能回收" << endl;
}
int n = pthread_join(_tid, nullptr);
if (n != 0)
{
cerr << "线程回收失败" << strerror(n) << endl;
}
else
{
cout << "线程回收成功" << endl;
}
}
调用pthread库内的pthread_join函数,注意如果线程已经分离就不能回收了。