在后端开发中,我们经常需要使用多线程,频繁的调用系统API创建线程比较繁琐,而且代码有冗余,所以对Linux以及win下的API进行封装。如下是代码实现
#ifndef __CTHREAD__H_
#define __CTHREAD__H_
#include "common.h"
#include "CMutex.h"
#include "Idle.h"
enum THREADSTATE
{
THREAD_STATE_INIT = 1, //线程初始化状态
THREAD_STATE_RUN, //线程运行状态
THREAD_STATE_SLEEP, //线程休眠状态
THREAD_STATE_WAIT_EXIT, //线程等待退出状态
THREAD_STATE_EXIT, //线程已经退出
};
enum THREADTYPE
{
THREAD_TYPE_CONTROL = 0, //线程被管理
THREAD_TYPE_AUTO_EXIT, //线程自动退出
};
class CThread
{
public:
CThread();
virtual ~CThread();
int GetThreadState(){ return miThreadState; }
void SetType(int iType){ miType = iType; }
public:
static void* ThreadEntry(void* pParam);
protected:
virtual void* work() = 0; //子类线程执行函数
protected:
//typedef void* (*thread_proc) (void *);
int Start(bool bWaitCreateSuccesss = true);
void Wait(unsigned long iTime = 500);
void Activate();
int AfterStop();
int Stop();
protected:
DWORD mdwThreadID;
protected:
bool mbStop;
int miType;
int miThreadState;
CMutex mcMutex;
CIdle mcIdle;
bool mbExitMainFunc;
};
#endif
#include "CThread.h"
#include "CLogmanager.h"
CThread::CThread()
{
mdwThreadID = 0;
mbStop = false;
mbExitMainFunc = false;
miThreadState = THREAD_STATE_INIT;
miType = THREAD_TYPE_CONTROL;
}
CThread::~CThread()
{
}
void CThread::Wait(unsigned long iTime)
{
if (miThreadState == THREAD_STATE_RUN)
{
miThreadState = THREAD_STATE_SLEEP;
mcIdle.Sleep(iTime);
miThreadState = THREAD_STATE_RUN;
}
}
void CThread::Activate()
{
if (miThreadState == THREAD_STATE_SLEEP)
{
mcIdle.Activate();
miThreadState = THREAD_STATE_RUN;
}
}
void* CThread::ThreadEntry(void* pParam)
{
void* pRet = nullptr;
CThread* pThread = reinterpret_cast<CThread*>(pParam);
if (nullptr != pThread)
{
pThread->miThreadState = THREAD_STATE_RUN;
pThread->mdwThreadID = get_thread_id_self();
pRet = pThread->work();
pThread->mbExitMainFunc = true;
#if defined(WIN32) || defined(_WIN32)
_endthread(); //自动回收资源
#elif __linux__
pthread_detach(pthread_self()); //自动回收资源
#endif
}
return pRet;
}
int CThread::Start(bool bWaitCreateSuccesss)
{
#if defined(WIN32) || defined(_WIN32)
if(_beginthread((void(__cdecl *) (void *))CThread::ThreadEntry, 0, (void*)this) == -1)
{
return 1;
}
#elif __linux__
if (::pthread_create((pthread_t*)&mdwThreadID, nullptr, CThread::ThreadEntry, (void*)this) != 0)
{
return 1;
}
#endif
while (bWaitCreateSuccesss && miThreadState != THREAD_STATE_RUN)
{
mcIdle.Sleep();
}
return 0;
}
int CThread::Stop()
{
mbStop = true;
Activate();
while (!mbExitMainFunc)
{
Wait();
}
return AfterStop();
}
int CThread::AfterStop()
{
miThreadState = THREAD_STATE_EXIT;
mdwThreadID = 0;
return 0;
}