#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 ) // Constructor implementation basicThread::basicThread(){ m_pLog = basicLogCollection::getInstance(); m_bThreadStatus = TH_PRE_INIT; }; // Destructor implementation basicThread::~basicThread(){ if (m_bThreadStatus > TH_ARMED ) { waitThreadEnd( true ); // JOIN in Wait function!! //pthread_detach(m_sThreadHandler); //pthread_join(m_sThreadHandler, NULL); }; }; bool basicThread::init( void ){ 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 Faled."); 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(); mThis->m_bThreadStatus = TH_EXIT; } else { SLOG_ERROR("Thread is not ARMED!"); }; #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, 2000); CloseHandle(m_hThreadHandle); #endif }; #undef LOG #undef LOG_ERROR #undef SLOG #undef SLOG_ERROR