Guyz, I'm still working my ass learning threading and currently making a simple WatchDog Thread using semaphore (FYI, this thread functions as a program's heartbeat to check whether the program freezes or not)
When I call the OnClose() method, it supposed to send a WatchDogKill semaphore and end the WatchDog thread, but the WatchDogKill didn't arrived at the thread, so the program immediately closes without exiting the thread loop. Anyone has any clue ??
CWinThread *WatchDogThread;
BOOL OnInitDialog()
{
WatchDogThread = NULL;
WatchDogThread=::AfxBeginThread( ThreadWatchDog, (void*) this, THREAD_PRIORITY_NORMAL );
}
void initSemaphore()
{
theApp.m_hWatchDogKill = ::CreateSemaphore( NULL, 0, 1, "WatchDogKill" );
theApp.m_hWatchDogEnd = ::CreateSemaphore( NULL, 0, 1, "WatchDogEnd" );
}
UINT ThreadWatchDog( LPVOID pParam )
{
::Sleep( 300 );
CBSysDlg *thisClass = (CBSysDlg *)pParam;
while( 1 )
{
DWORD dWait = ::WaitForSingleObject( theApp.m_hWatchDogKill, 1000 );
switch( dWait )
{
case WAIT_OBJECT_0: break;
default:
{
thisClass->sendWatchDogSignal(thisClass->m_oTrigger.getId());
continue;
}
}
break;
}
::ReleaseSemaphore(theApp.m_hWatchDogEnd,1,NULL);
return(0);
}
void CBSysDlg::sendWatchDogSignal(short triggerID)
{
if(watchDogStatus==FALSE)
{
watchDogStatus=TRUE;
sendSignal(O_WATCH_DOG_TIMER, IO_ON);
}
else
{
watchDogStatus=FALSE;
sendSignal(O_WATCH_DOG_TIMER, IO_OFF);
}
}
void CBSysDlg::endWatchDog()
{
if (WatchDogThread) {
BOOL retcode = ::ReleaseSemaphore(theApp.m_hWatchDogKill, 1, NULL);
DWORD err=GetLastError();
if (::WaitForSingleObject(theApp.m_hWatchDogEnd,2000) == WAIT_TIMEOUT) {
::TerminateThread(WatchDogThread->m_hThread,1);
}
::Sleep(10);
WatchDogThread=NULL;
}
CloseHandle(theApp.m_hWatchDogKill);
CloseHandle(theApp.m_hWatchDogEnd);
}
void OnClose()
{
endWatchDog();
CWnd::OnClose();
}