#include "basicThread.h" #define LOG( X ) m_pLog->Log( "BasicThread", this, X ) #define LOG_ERROR( X ) m_pLog->Log( "BasicThread", this, _LOG_ERROR, X ) //Thread Logging #define SLOG( X ) mThis->m_pLog->Log( "BasicThreadS", mThis, X ) #define SLOG_ERROR( X ) mThis->m_pLog->Log( "BasicThreadS", mThis, _LOG_ERROR, X ) bool basicThread::init( void ){ #ifdef DEBUG_EXTRA LOG("Init Single Thread"); #endif if( m_bThreadStatus == TH_PRE_INIT ){ m_bThreadStatus = TH_ARMED; #if defined( __linux__ ) || defined(WIN_PTHREAD) int RetVal = pthread_create( &m_sThreadHandler, NULL, m_fThreadEntryPoint, ( void * ) this ); if( RetVal == -1 ) { LOG_ERROR("Thread Creation Failed."); return false; }; #else m_hThreadHandle = CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)m_fThreadEntryPoint, (LPVOID)this, 0, &m_dwThreadID ); //TODO: Add thread creation check #endif } else { LOG_ERROR("Thread object not ready to be created."); return false; }; return true; }; void basicThread::m_fThreadProc( void ){ m_bThreadStatus = TH_WORKING; while( m_bThreadStatus < TH_ENDED ) { SLEEP( DEFAULT_THREAD_SLEEP_TIME ); }; }; #if defined( __linux__ ) || defined(WIN_PTHREAD) void *basicThread::m_fThreadEntryPoint( void *ptr ){ #else DWORD WINAPI basicThread::m_fThreadEntryPoint( LPVOID ptr){ #endif basicThread *mThis; mThis = ( basicThread * ) ptr; if( mThis->m_bThreadStatus == TH_ARMED ) { mThis->m_fThreadProc(); } else { SLOG_ERROR("Thread is not ARMED!"); }; mThis->m_bThreadStatus = TH_EXIT; #ifdef __linux__ pthread_exit( NULL ); return NULL; #else return 0; #endif }; void basicThread::waitThreadEnd(bool forced){ if( m_bThreadStatus > TH_WORKING || m_bThreadStatus < TH_ARMED ) return; if( forced ) m_bThreadStatus = TH_ENDED; while (m_bThreadStatus != TH_EXIT) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); #if defined( __linux__ ) || defined(WIN_PTHREAD) pthread_join(m_sThreadHandler, NULL); #else WaitForSingleObject(m_hThreadHandle, DEFAULT_THREAD_SLEEP_TIME); CloseHandle(m_hThreadHandle); #endif }; bool basicThread::uninit( void ){ if( m_bThreadStatus == TH_PRE_INIT ) return true; //If Thread about to start -> Wait till it starts if( m_bThreadStatus == TH_ARMED ) while( m_bThreadStatus < TH_WORKING ) SLEEP( DEFAULT_THREAD_SLEEP_TIME ); if( m_bThreadStatus == TH_WORKING ) m_bThreadStatus = TH_ENDED; if( m_bThreadStatus > TH_WORKING ){ #if defined( __linux__ ) || defined(WIN_PTHREAD) pthread_join(m_sThreadHandler, NULL); #else WaitForSingleObject(m_hThreadHandle, DEFAULT_THREAD_SLEEP_TIME); CloseHandle(m_hThreadHandle); #endif }; m_bThreadStatus = TH_PRE_INIT; return true; }; void basicThread::abort(){ pthread_cancel( m_sThreadHandler ); pthread_join( m_sThreadHandler, NULL); }; #undef LOG #undef LOG_ERROR #undef SLOG #undef SLOG_ERROR