您的位置:首页 > 其它

游戏服务器之线程封装

2014-07-07 15:21 232 查看
其他具体线程类型需要继承线程基类,来实现线程控制和业务循环。

1、线程初始化和析构

线程基类初始化和析构:

1)线程包含互斥量和条件变量

2)初始化需要唤醒线程(解除阻塞等待)

3)析构时(在对象析构时实现,避免手动处理,但对象需要在进程终结前析构),需要处理的业务终止控制(需要按顺序执行):

1>终止该线程业务循环

2>取消该线程

3>回收该线程资源

CBaseThread::CBaseThread()
{
m_pid = 0;
m_isBlock = false;
pthread_mutex_init(&m_blockMutex, 0);//互斥量
pthread_cond_init(&m_blockCond, 0);//条件变量
createThread();
}
CBaseThread::CBaseThread(bool boCreateSuspended)
{
m_pid = 0;
m_isBlock = true;//开始时被阻塞
pthread_mutex_init(&m_blockMutex, 0);//初始化互斥量
pthread_cond_init(&m_blockCond, 0);//初始化环境变量
createThread();
}
CBaseThread::~CBaseThread()
{
pthread_mutex_destroy(&m_blockMutex);//销毁互斥量
pthread_cond_destroy(&m_blockCond);//销毁环境变量
}


在线程对象构造和析构函数中实现子线程初始化和终止
CAccountManager::CAccountManager()
:super(TRUE)
{
......
m_boStarted = FALSE;
resume();//发信号唤醒阻塞中的子线程(如果子线程没有阻塞则不起什么作用)
}

CAccountManager::~CAccountManager()
{
stopManager();//停止该线程业务(终止该线程业务循环)
terminate();//关闭该线程(取消该线程)
waitFor();//回收子线程资源(必须使用pthread_join等待并回收子线程资源后再执行,否则可能会有段错误)
}


2、线程控制

具体线程对象中的业务循环的启动业务和终止业务
//开始具体线程对象的业务循环
bool CAccountManager::startManager()
{
if (!m_boStarted)
{
m_boStarted = TRUE;
}
return true;
}
//终止具体线程对象的业务循环
void CAccountManager::stopManager()
{
if (m_boStarted)
{
m_boStarted = FALSE;
}
}

//线程挂起
int CBaseThread::suspend()
{
m_isBlock = true; //阻塞标识
return 0;
}

//线程唤醒
int CBaseThread::resume()
{
m_isBlock = false;//非阻塞
pthread_cond_signal(&m_blockCond);//发信号到条件变量
return 0;
}

//获取线程优先级
int CBaseThread::getPriority()
{
int policy;
sched_param sp;
if(0 != pthread_getschedparam(m_pid, &policy, &sp))
{
return 0;
}
return sp.sched_priority;//获取优先级
}

//设置线程优先级
bool CBaseThread::setPriority(int nPriority)
{
sched_param sp = {nPriority};
if(0 == pthread_setschedparam(m_pid, SCHED_RR, &sp))//设置优先级
{
return true;
}
return false;
}

//终结线程
void CBaseThread::terminate()
{
pthread_cancel(m_pid);//取消线程
m_boTerminated = true;
}

//连接线程,等待回收该线程资源
int CBaseThread::waitFor()
{
pthread_join(m_pid, 0);//等待回收该线程资源
return 0;
}

//创建线程
void CBaseThread::createThread()
{
pthread_create(&m_pid, 0, (LPTHREAD_START_ROUTINE)(&CBaseThread::threadRoutine), this);
}

//线程循环
void *CBaseThread::threadRoutine(CBaseThread *lpThread)
{
lpThread->OnRountine();
lpThread->OnTerminated();
pthread_exit(0);
m_boTerminated = true;//该线程结束标记
return NULL;
}

//判断是否阻塞而等待信号
inline bool blocking()
{
if(m_isBlock)
{
pthread_mutex_lock(&m_blockMutex);
pthread_cond_wait(&m_blockCond, &m_blockMutex);
pthread_mutex_unlock(&m_blockMutex);
}
return true;
}

inline bool terminated(){ return m_boTerminated; }//判断是否终止了


3、线程循环

在子类线程中实现具体线程业务循环,例子如CAccountManager 

class CAccountManager :public lib::thread::CBaseThread

实现循环虚函数
void CAccountManager::OnRountine()
{
while (!terminated())
{
if (m_boStarted)//处理业务
{
......
}
moon::OS::osSleep(1);
}
}


如果有需要可以在循环中再判断是否阻塞。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: