考慮到線程天然結束對釋放資源比較友好,因而想了個辦法,對線程進行了封裝,方便之後工做中進行復用。this
代碼以下:線程
#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; };