Click here to Skip to main content
15,999,481 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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 ??

C++
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();

		// Wait for info that thread is killed
		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();
}
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900