线程基类

每次创建线程相当麻烦,总是不记得一些参数和细节;

现在将线程的创建封装成一个基类,只要继承该基类,调用Start(),就可以得到一个一直运行的OnRun线程,非常方便。

//ThreadBase.h
#ifndef _THREADBASE_H_
#define _THREADBASE_H_

#include <Windows.h>
#include <string>
using namespace std;

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

	//启动线程
	void					Start();

	//停止线程
	void					Stop();

	/***********************************************************************
	/*必须重载OnRun虚函数,Start()以后,线程进入OnRun();
	/*返回非0,退出线程
	/************************************************************************/
	virtual int			OnRun()=0;
protected:
private:
	unsigned int static __stdcall  ThreadFunc(void *pData);

	HANDLE					m_hThread;
	bool					m_bNeedStop;
};

#endif

//ThreadBase.cpp
#include "ThreadBase.h"
#include <process.h>

CThreadBase::CThreadBase()
{
	m_hThread = NULL;
	m_bNeedStop = false;
}

CThreadBase::~CThreadBase()
{
	if(m_hThread)
	CloseHandle(m_hThread);
	m_hThread = NULL;
}

void CThreadBase::Start()
{
	m_hThread = (HANDLE)_beginthreadex(NULL,NULL,&ThreadFunc,this,NULL,NULL);
}

void CThreadBase::Stop()
{
	if(m_hThread)
		CloseHandle(m_hThread);
	m_hThread = NULL;
	m_bNeedStop = true;
}

unsigned int CThreadBase::ThreadFunc(void *pData)
{
	if(pData == NULL)
		return -1;

	CThreadBase *pBase = (CThreadBase*)pData;

	while(!pBase->m_bNeedStop)
	{
		int nRet = pBase->OnRun();
		if(nRet != 0)
			return nRet;
	}
	return 0;
}

以上便是整个基类代码。

===========================================   分割线   =====================================================

以下是一个调用测试程序:

//myThread.h
#ifndef _MYTHREAD_H_
#define _MYTHREAD_H_

#include "ThreadBase.h"

class CmyThread:public CThreadBase
{
public:
	CmyThread();
	~CmyThread();

	virtual int OnRun();
};
#endif

//myThread.cpp
#include "ThreadBase.h"
#include <process.h>

CThreadBase::CThreadBase()
{
	m_hThread = NULL;
	m_bNeedStop = false;
}

CThreadBase::~CThreadBase()
{
	if(m_hThread)
	CloseHandle(m_hThread);
	m_hThread = NULL;
}

void CThreadBase::Start()
{
	m_hThread = (HANDLE)_beginthreadex(NULL,NULL,&ThreadFunc,this,NULL,NULL);
}

void CThreadBase::Stop()
{
	if(m_hThread)
		CloseHandle(m_hThread);
	m_hThread = NULL;
	m_bNeedStop = true;
}

unsigned int CThreadBase::ThreadFunc(void *pData)
{
	if(pData == NULL)
		return -1;

	CThreadBase *pBase = (CThreadBase*)pData;

	while(!pBase->m_bNeedStop)
	{
		int nRet = pBase->OnRun();
		if(nRet != 0)
			return nRet;
	}
	return 0;
}


主程序

//main.cpp
#include "myThread.h"
int _tmain(int argc, char **argv)
{
	CmyThread myThread1;
	CmyThread myThread2;
	CmyThread myThread3;
	system("pause");
	return 0;
}


执行结果:


posted on 2017-10-12 21:27  zhuxian2009  阅读(272)  评论(0)    收藏  举报

导航