Linux学习之线程封装四:基于接口的封装

业务逻辑提供者类"CLThreadFunctionProvider"

头文件:

View Code
#ifndef CLTHREADFUNCTIONPROVIDER_H
#define CLTHREADFUNCTIONPROVIDER_H

#include "CLStatus.h"

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

public:
virtual CLStatus RunThreadFunction(void *pContext) = 0;

private:
CLThreadFunctionProvider(const CLThreadFunctionProvider&);
CLThreadFunctionProvider& operator=(const CLThreadFunctionProvider&);
};

#endif

抽象类,用户自己提供业务逻辑,私有化复制构造函数和“=”操作符,保证对象访问的唯一性。
实现:

View Code
#include "CLThreadFunctionProvider.h"

CLThreadFunctionProvider::CLThreadFunctionProvider()
{
}

CLThreadFunctionProvider::~CLThreadFunctionProvider()
{
}

具体由用户实现。
线程类"CLThread"

头文件:

View Code
#ifndef CLTHREAD_H
#define CLTHREAD_H

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

class CLThreadFunctionProvider;

class CLThread
{
public:
CLThread(CLThreadFunctionProvider *pThreadFunctionProvider);
virtual ~CLThread();

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

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

protected:
void *m_pContext;
pthread_t m_ThreadID;

CLThreadFunctionProvider *m_pThreadFunctionProvider;
};

#endif

CLThreadFunctionProvider再投文件中只需声明,无需include "CLThreadFunctionProvider.h",因为没有用到具体的成员。
实现:

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

CLThread::CLThread(CLThreadFunctionProvider *pThreadFunctionProvider)
{
m_pThreadFunctionProvider = pThreadFunctionProvider;

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->m_pThreadFunctionProvider->RunThreadFunction(pThreadThis->m_pContext);

return (void *)s.m_clReturnCode;
}

调用:

View Code
#include <iostream>
#include <unistd.h>
#include "CLThread.h"
#include "CLThreadFunctionProvider.h"

using namespace std;

class CLParaPrinter : public CLThreadFunctionProvider
{
public:
CLParaPrinter()
{
}

virtual ~CLParaPrinter()
{
}

virtual CLStatus RunThreadFunction(void *pContext)
{
int i = (int)pContext;
cout << i << endl;
}
};

int main()
{
CLParaPrinter *printer = new CLParaPrinter();
CLThread *pThread = new CLThread(printer);

pThread->Run((void *)2);
pThread->WaitForDeath();

delete pThread;
delete printer;

return 0;
}




posted @ 2011-10-19 21:41  lq0729  阅读(451)  评论(0编辑  收藏  举报