Linux学习之线程封装二:面向对象的封装

线程类"CLThread"

头文件:

View Code
#ifndef CLTHREAD_H
#define CLTHREAD_H

#include <pthread.h>
#include "CLStatus.h"

class CLThread
{
public:
CLThread();
virtual ~CLThread();

CLStatus Run(void *pContext = 0);
CLStatus WaitForDeath();

private:
static void* StartFunctionOfThread(void *pContext);

protected:
virtual CLStatus RunThreadFunction() = 0;

void *m_pContext;
pthread_t m_ThreadID;
};

#endif

实现文件:

View Code
#include "CLThread.h"
#include "CLLog.h"

CLThread::CLThread()
{
m_pContext = 0;
}

CLThread::~CLThread()
{
}

CLStatus CLThread::Run(void *pContext)
{
m_pContext = pContext;

int r = pthread_create(&m_ThreadID, 0, StartFunctionOfThread, this);
if(r != 0)
{
CLLog::WriteLogMsg("In CLThread::Run(), pthread_create error", r);
return CLStatus(-1, 0);
}

return CLStatus(0, 0);
}

CLStatus CLThread::WaitForDeath()
{
int r = pthread_join(m_ThreadID, 0);
if(r != 0)
{
CLLog::WriteLogMsg("In CLThread::WaitForDeath(), pthread_join error", r);
return CLStatus(-1, 0);
}

return CLStatus(0, 0);
}

void* CLThread::StartFunctionOfThread(void *pThis)
{
CLThread *pThreadThis = (CLThread *)pThis;

CLStatus s = pThreadThis->RunThreadFunction();

return (void *)s.m_clReturnCode;
}

析构函数声明为virtual,以便子类在析构时能清理自己添加的成员以及做些必要的处理。
实际的执行方法声明为纯虚函数,以承载不同的业务逻辑。


posted @ 2011-10-19 20:17  lq0729  阅读(284)  评论(0编辑  收藏  举报