线程简单封装

#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();
	virtual int GetThreadState(){ return m_iThreadState; }
	void SetType(int iType){ m_iType = iType; }

public:
	static void* ThreadEntry(void* pParam);

protected:
	virtual void* work() = 0;	//子类线程执行函数

protected:
	//typedef void* (*thread_proc) (void *);
	int Start();
	void Wait(unsigned long iTime = 500);
	void Activate();
	int AfterStop();
	int Stop();

protected:
	DWORD m_dwThreadID;

protected:
	bool m_bStop;
	int m_iType;
	int m_iThreadState;
	CMutex m_cMutex;
	CIdle m_cIdle;
	bool m_bExitMainFunc;
};

#endif


#include "stdafx.h"
#include "CThread.h"
#include "CLogmanager.h"
CThread::CThread()
{
	m_dwThreadID = 0;
	m_bStop = false;
	m_bExitMainFunc = false;
	m_iThreadState = THREAD_STATE_INIT;
	m_iType = THREAD_TYPE_CONTROL;
}

CThread::~CThread()
{
}

void CThread::Wait(unsigned long iTime)
{
	m_iThreadState = THREAD_STATE_SLEEP;
	m_cIdle.Sleep(iTime);
	m_iThreadState = THREAD_STATE_RUN;
}

void CThread::Activate()
{
	if (m_iThreadState == THREAD_STATE_SLEEP)
	{
		m_cIdle.Activate();
		m_iThreadState = THREAD_STATE_RUN;
	}
}

void* CThread::ThreadEntry(void* pParam)
{
	void* pRet = nullptr;

	CThread* pThread = reinterpret_cast<CThread*>(pParam);
	if (nullptr != pThread)
	{
		pThread->m_dwThreadID = get_thread_id_self();
		pRet = pThread->work();
		pThread->m_bExitMainFunc = true;
#if defined(WIN32) || defined(_WIN32)
		_endthread();	//自动回收资源
#elif  __linux__
#endif
	}

	return pRet;
}

int CThread::Start()
{
#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*)&m_dwThreadID, nullptr, CThread::ThreadEntry, (void*)this) != 0)
	{
		return 1;
	}
#endif

	m_iThreadState = THREAD_STATE_RUN;
	return 0;
}

int CThread::Stop()
{
	m_bStop = true;
	Activate();
	while (!m_bExitMainFunc)
	{
		Wait();
	}

	return AfterStop();
}

int CThread::AfterStop()
{
	m_iThreadState = THREAD_STATE_EXIT;
#if defined(WIN32) || defined(_WIN32)
#elif  __linux__
	pthread_join((pthread_t)(m_dwThreadID), nullptr);
#endif

	m_dwThreadID = 0;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/lightjia/article/details/79897109