Linux学习之线程封装一:基于对象的封装
线程类“CLThread”
头文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#ifndef CLTHREAD_H
#define CLTHREAD_H
#include <pthread.h>
#include "CLStatus.h"
class CLThread
{
public:
CLThread();
~CLThread();
CLStatus Run(void *pContext = 0);
CLStatus WaitForDeath();
private:
static void* StartFunctionOfThread(void *pContext);
private:
CLStatus RunThreadFunction();
private:
void *m_pContext;
pthread_t m_ThreadID;
};
#endif
实现文件:
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <iostream>
#include "CLThread.h"
#include "CLLog.h"
using namespace std;
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;
}
CLStatus CLThread::RunThreadFunction()
{
cout << (int)m_pContext << endl;
return CLStatus(0, 0);
}
为什么使用static函数?
为了与pthread_create()的参数匹配:pthread_create()的第三个为void*(*start_rtn)(void*)。显然,类的普通成员函数第一个参数为隐藏的this指针,这与前面的类型不相符;编译器也会提示错误。这个参数只能是全局函数或类的静态成员函数。
为什么使用StartFunctionOfThread()而不直接声明RunThreadFunction()为static且把其作为参数传递给pthread_create()?
首先,如上个问题所述,若作为参数,限制了其参数和返回值类型,不便提供灵活的应用。本例中,返回值就不能用CLStatus等复杂数据类型,只能是可以转换为(void *)的类型。
其次,StartFunctionOfThread()相当与一个中间的管理层,它可以对参数(本例是this)和返回值进行有意义的控制和处理。