Linux学习之线程封装三:基于模板的面向对象的封装

头文件:

View Code
#ifndef CLTHREAD_H
#define CLTHREAD_H

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

template<typename T>
class CLThread
{
public:
CLThread(){}
~CLThread(){}

CLStatus Run(void *pContext = 0)
{
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 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);
}

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

T *pThreadThis = (T *)pContext;

CLStatus s = pThreadThis->RunThreadFunction();

return (void *)s.m_clReturnCode;
}

CLStatus RunThreadFunction()
{
return CLStatus(-1, 0);
}

protected:
void *m_pContext;
pthread_t m_ThreadID;
};

#endif

调用:

View Code
class CLMyThread : public CLThread<CLMyThread>
{
public:
CLStatus RunThreadFunction()
{
int i = (int)m_pContext;
cout << i << endl;
}
};

实现了静态的多态。


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