线程类"CLThread"
头文件:
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#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
实现文件:
![ContractedBlock.gif](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![ExpandedBlockStart.gif](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#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,以便子类在析构时能清理自己添加的成员以及做些必要的处理。
实际的执行方法声明为纯虚函数,以承载不同的业务逻辑。