线程封装

考虑到线程自然结束对释放资源比较友好,于是想了个办法,对线程进行了封装,方便以后工作中进行复用。

代码如下:

#pragma once

#include "./vos/vos.h"

typedef void (*ThreadExcuteFun)(void* );

class VOSThreadObject
{
public:
	VOSThreadObject(ThreadExcuteFun fun, void* funPara, int cycleTime = 0/*循环调用fun的间隔时间*/) 
		:	m_isRunning(false)
	{
		CreateStopEvent();

		StartThread(fun, funPara, cycleTime);
	}

	~VOSThreadObject() 
	{
		StopThread();

		ReleaseStopEvent();
	}

private:

	void StartThread(ThreadExcuteFun fun, void* funPara, int cycleTime = 0/*循环调用fun的间隔时间*/)
	{
		m_pExecuteFunPara = funPara;
		m_CycExecuteFun = fun;
		m_CycIntervalTime = cycleTime;

		VOS_Thread	threadData;
		VOS_Thread* pThread = &threadData;
		VOS_CreateThread(ThreadEntry, this, &pThread, 0);
	}

	void StopThread()
	{
		if(!IsRunning())
			return;

		VOS_SetEvent(&m_StopThreadEvent);

		while (IsRunning())
		{
			VOS_Sleep(1);
		}
	}

#if VOS_APP_OS == VOS_OS_WIN32
	static ULONG __stdcall ThreadEntry(VOID *lpvoid)
#else
	static VOID* ThreadEntry(VOID *lpvoid)
#endif
	{
		VOSThreadObject* pObj = (VOSThreadObject*)lpvoid;

		pObj->SetIsRunning(true);

		while (1)
		{
			//调用执行体
			pObj->m_CycExecuteFun(pObj->m_pExecuteFunPara);

			//检查到退出信号就退出线程
			if(VOS_ERR_QUE_TIMEOUT != VOS_WaitEvent(&pObj->m_StopThreadEvent, 0))
				break;

			//等待循环调用间隔时间
			VOS_Sleep(pObj->m_CycIntervalTime);
		}

		pObj->SetIsRunning( false);

		return 0;
	}

	bool IsRunning()
	{
		return m_isRunning;
	}

	void SetIsRunning(bool isRunning)
	{
		m_isRunning = isRunning;
	}

	void CreateStopEvent()
	{
		VOS_CreateEvent(&m_StopThreadEvent);
	}

	void ReleaseStopEvent()
	{
		VOS_DestroyEvent(&m_StopThreadEvent);
	}

private:
	bool				m_isRunning;
	VOS_Event			m_StopThreadEvent;

	int					m_CycIntervalTime;
	ThreadExcuteFun		m_CycExecuteFun;
	void*				m_pExecuteFunPara;
};

你可能感兴趣的:(线程封装)