//---------------------------------------------------------------------------- // Laser Guard Ltd. // Copyright © 2000-2002. All Rights Reserved. // Version 1.0 01/01/2000 // Last modification: 03/09/2001 // PROJECT: // SUBSYSTEM: // FILE: Thread1.cpp // AUTHOR: Sergey Chizhevskiy // OVERVIEW // ~~~~~~~~ // Source file of Thread1.cpp //---------------------------------------------------------------------------- #include "stdafx.h" #include #include "Thread.h" CThread::CThread() { // erase all data m_dwThreadId = 0UL; m_hEventStopThread = NULL; m_hThread = NULL; m_bSelfDestroy = FALSE; } CThread::~CThread() { // if it is not self destroy if( !m_bSelfDestroy ) Stop( TRUE ); } BOOL CThread::Start( BOOL bSelfDestroy ) { // blocking stop if thread was ran before if( !Stop( TRUE ) ) return FALSE; // store for future use m_bSelfDestroy = bSelfDestroy; // create event for thread's stopping m_hEventStopThread = ::CreateEvent( NULL, FALSE, FALSE, NULL ); if( !m_hEventStopThread ) return FALSE; // create new thread m_hThread = (HANDLE)_beginthreadex( NULL, 0, ThreadProc, this, 0, (PUINT)&m_dwThreadId ); if( !m_hThread ) return FALSE; // all work was done successefully return TRUE; } BOOL CThread::Stop( BOOL bWaitForComplete ) { // force thread to close if( m_hEventStopThread ) ::SetEvent( m_hEventStopThread ); // if don't need to wait until thread will closed if( !bWaitForComplete ) return TRUE; // prevent dead lock if tryed to close from thread itself if( m_dwThreadId == ::GetCurrentThreadId() ) return FALSE; // assume success BOOL bResult = TRUE; // if thread exists and works if( m_hThread ) { // wait until thread will closed bResult = ::WaitForSingleObject( m_hThread, MAX_THREAD_CLOSE_TIME ) == WAIT_OBJECT_0; // if thread doesn't closed normally if( !bResult ) _endthreadex( (UINT)m_hThread ); // close thread handle ::CloseHandle( m_hThread ); // erase old value m_hThread = NULL; } // if event handle is valid if( m_hEventStopThread ) { // close event handle ::CloseHandle( m_hEventStopThread ); // erase old value m_hEventStopThread = NULL; } // return result of close operation return bResult; } UINT CALLBACK CThread::ThreadProc( LPVOID lpvParam ) { // get pointer to this CThread *pThread = (CThread*) lpvParam; // call thread procedure UINT nResult = pThread->ThreadProc(); // ensure to close thread normally // _endthreadex( (UINT)nResult ); // self destroy if nessessary if( pThread->m_bSelfDestroy ) { // close event handle if( pThread->m_hEventStopThread ) ::CloseHandle( pThread->m_hEventStopThread ); // close thread handle if( pThread->m_hThread ) ::CloseHandle( pThread->m_hThread ); // delete itself delete pThread; } //return with result return nResult; }