#ifndef THREAD_H #define THREAD_H // thread.h is based on Thread by Jori Liesenborgs (jori@lumumba.luc.ac.be) #ifdef WIN32 #include #else // posix #include #include #endif #define ERR_MUTEX_ALREADYINIT -1 #define ERR_MUTEX_NOTINIT -2 #define ERR_MUTEX_CANTCREATEMUTEX -3 #define ERR_THREAD_CANTINITMUTEX -1 #define ERR_THREAD_CANTSTARTTHREAD -2 #define ERR_THREAD_THREADFUNCNOTSET -3 #define ERR_THREAD_NOTRUNNING -4 #define ERR_THREAD_ALREADYRUNNING -5 #if 0 class Mutex { bool locked; public: Mutex() { locked = false; } inline void lock() { while (locked); locked = true; } inline void unlock() { locked = false; } }; #else class Mutex { public: Mutex() { initialized = false; if (initialized) throw ERR_MUTEX_ALREADYINIT; #ifdef WIN32 mutex = CreateMutex(NULL,FALSE,NULL); if (mutex == NULL) throw ERR_MUTEX_CANTCREATEMUTEX; #else pthread_mutex_init(&mutex,NULL); #endif initialized = true; } ~Mutex() { if (initialized) #ifdef WIN32 CloseHandle(mutex); #else pthread_mutex_destroy(&mutex); #endif } inline void lock() { if (!initialized) throw ERR_MUTEX_NOTINIT; #ifdef WIN32 WaitForSingleObject(mutex,INFINITE); #else pthread_mutex_lock(&mutex); #endif } inline void unlock() { if (!initialized) throw ERR_MUTEX_NOTINIT; #ifdef WIN32 ReleaseMutex(mutex); #else pthread_mutex_unlock(&mutex); #endif } bool isInitialized() { return initialized; } private: #ifdef WIN32 HANDLE mutex; #else pthread_mutex_t mutex; #endif bool initialized; }; #endif // Mutex class Thread { public: Thread() { alive = false; } virtual ~Thread() { kill(); } void start() { #ifndef WIN32 int status; #endif if (alive) throw ERR_THREAD_ALREADYRUNNING; init_mutex.lock(); #ifdef WIN32 threadhandle = CreateThread(NULL,0,entryPoint,this,0,&threadid); if (threadhandle == NULL) { #else status = pthread_create(&threadid,NULL,entryPoint,this); if (status != 0) { #endif init_mutex.unlock(); throw ERR_THREAD_CANTSTARTTHREAD; } // wait until run() is executed while (!alive); init_mutex.unlock(); } void kill() { #ifdef WIN32 TerminateThread(threadhandle,0); #else pthread_cancel(threadid); #endif alive = false; } virtual void run() { } inline bool isAlive() { return alive; } private: #ifdef WIN32 HANDLE threadhandle; DWORD threadid; static DWORD WINAPI entryPoint(void *param) { #else pthread_t threadid; static void *entryPoint(void *param) { #endif Thread *thread; thread = (Thread *)param; thread->alive = true; // wait until start() had been finished thread->init_mutex.lock(); thread->init_mutex.unlock(); thread->run(); thread->alive = false; #ifdef WIN32 return 0; #else return NULL; #endif } bool alive; Mutex init_mutex; }; #endif // THREAD_H