从零开始构建一个Reactor模式的网络库(二)线程类Thread

时间:2023-03-09 04:01:37
从零开始构建一个Reactor模式的网络库(二)线程类Thread

线程类Thread是对POSIX线程的封装类,因为要构建的是一个Linux环境下的多线程网络库,对线程的封装是很必要的。

首先是CurrentThread命名空间,主要是获取以及缓存线程id:

 #ifndef CURRENTTHREAD_H
#define CURRENTTHREAD_H
#include <unistd.h>
#include <sys/syscall.h> namespace CurrentThread
{
extern __thread int t_cachedTid;
inline void cacheTid()
{
t_cachedTid=static_cast<int>(::syscall(SYS_gettid));
}
inline int tid()
{
if(t_cachedTid==)
cacheTid();
return t_cachedTid;
}
} #endif // CURRENTTHREAD_H

这里要注意一个问题,就是线程id的获取

线程id的获取可以通过几种方式,最方便的是syscall(),是一个glibc库函数而不是一个系统调用,此时返回的是内核中的线程id。

因为Linux的线程实现中,线程事实上也是一个进程,因此返回的tid事实上就是pid,pid_t在Linux中一般实现为int。

另外,POSIX线程库提供了函数pthread_self(),但是该函数返回的是进程中的线程id,类型为pthread_t,一般是unsigned long类型,并不是内核中的实际id,在调试和排查错误时并不方便。

 #ifndef THREAD_H
#define THREAD_H
#include <pthread.h>
#include <memory>
#include <functional>
#include "Types.h"
#include <atomic>
#include "Mutex.h" namespace mini
{
class Thread
{
public:
typedef std::function<void()> ThreadFunc;
explicit Thread(const ThreadFunc& func,const string& ThreadName=string());
~Thread(); int join();
void start();
pid_t tid() const { return *tid_; }
bool started() const { return started_; }
const string& name() const {return name_;}
private: void setDefaultName(); bool started_; //if the thread started
bool joined_; //if joined settled
pthread_t pthreadId_; //thread id in the process
std::shared_ptr<pid_t> tid_; //shared_ptr to the tid
string name_; //name of the thread
ThreadFunc func_; //function for the thread
static std::atomic<int> numsCreated_; //record nums of created threads
}; } #endif // THREAD_H

Thread.h头文件中定义了Thread类,成员包括启动状态、tid和pthreadid、实际执行的函数以及名字等。

 #include "CurrentThread.h"
#include "Thread.h"
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/types.h> namespace CurrentThread
{
__thread int t_cachedTid=;
/*
bool isMainThread()
{
return ::getpid()==tid();
}
*/
}
namespace mini
{
struct ThreadData
{
typedef mini::Thread::ThreadFunc ThreadFunc;
ThreadFunc func_;
mini::string name_;
std::weak_ptr<pid_t> wkTid_;
ThreadData(const ThreadFunc& func,const string& name,const std::shared_ptr<pid_t>& tid)
:func_(func),name_(name),wkTid_(tid)
{}
void runInThread()
{
pid_t tid=CurrentThread::tid();
std::shared_ptr<pid_t> ptid=wkTid_.lock();
if(ptid)
{
*ptid=tid;
ptid.reset();
}
func_();
} };
std::atomic<int> Thread::numsCreated_(); void Thread::setDefaultName()
{
int num=numsCreated_++;
if(name_.empty())
{
char buf[];
snprintf(buf,sizeof buf,"Thread%d", num);
name_=buf;
}
} void* startThread(void* obj)
{
ThreadData* data=static_cast<ThreadData*>(obj);
data->runInThread();
delete data;
return NULL;
} Thread::Thread(const ThreadFunc &func, const string &ThreadName)
:started_(false),
joined_(false),
pthreadId_(),
tid_(new pid_t()),
func_(func),
name_(ThreadName)
{
setDefaultName();
} void Thread::start()
{
started_=true;
ThreadData* data=new ThreadData(func_,name_,tid_);
if(pthread_create(&pthreadId_,NULL,&startThread,data));
{
started_=false;
//delete data;
//LOG_SYSFATAL<<"FAILED in pthread_create";
}
} int Thread::join()
{
joined_=true;
return pthread_join(pthreadId_,NULL);
} Thread::~Thread()
{
if(started_&&!joined_)
pthread_detach(pthreadId_);
}
}

由于向pthread_create中传递要执行的线程函数以及参数比较复杂,定义了一个内部类ThreadData。

ThreadData中有一个weak_ptr<pid_t>,当线程实际被创建并开始运行时,创建一个临时的shared_ptr,确保Thread以及ThreadData被正确创建。

事实上,Thread类对象创建时,线程并没有实际开始运行,直到调用start()才开始执行。

执行线程可以调用join()来等待Thread线程的结束。默认情况下,线程资源会保留直到调用pthread_join()。

析构函数简单地调用pthread_detach()来设置线程分离,从而在线程函数执行结束后直接退出,线程资源也会在线程终止时立即被回收