/***************************************************** ** Thread.h ** ** -------- ** ** ** ** A very simple thread class built on top of the ** ** pthread library. It allows you to create a ** ** new thread that starts execution from an ** ** aplication defined entry point with a ** ** function prototype of the form: ** ** void *MyEntryFunction( void *argument); ** ** Also implemented are very basic thread query ** ** operations to determine if it is currently ** ** running (IsRunning()) and to check the ** ** application-defined threadID (GetThreadID()). ** ** A function to kill the thread externally is ** ** implemented via Kill(), though this is not ** ** particularly robust, given that no signal ** ** handling is defined. ** ** ** ** ** ** Chris Wyman (2/12/2007) ** *****************************************************/ #ifndef SIMPLE_THREAD_CLASS_H #define SIMPLE_THREAD_CLASS_H #include #include #include class Thread { public: // Initialize a thread with an application-specific ID number. Thread( int threadID=0 ) : threadID(threadID), isRunning(false) {} ~Thread() {} // Create a thread whose entry point is the function void *entryPoint( void *) // The argument passed to the entry point is "this" (the thread). bool Create( void *(*entryPoint)(void *) ); // Finishes the thread's execution. This should only be called by the thread itself. void Exit( void ); // Attempts to kill the thread. This function should not be called _by_ the thread // (which should call Exit() to finish), but rather by another process that wishes // to kill the thread. int Kill( int signal=SIGTERM ); // Returns a boolean if this thread is running. See the note on the isRunning variable // about validity of this result. inline bool IsRunning( void ) { return isRunning; } // Get the thread's integer identifier (This is not a process ID, but a application defined ID) inline int GetThreadID( void ) { return threadID; } private: int threadID; // An identifier for the thread pthread_t threadData; // The thread data used for pthread_*() calls // A variable queriable to check if the thread is running. Note that this // IS NOT protected by a mutex. Querying this variable is valid as long // as Create() or Exit() is not currently running. The two races on this // variable that give the wrong answer are: // 1) The thread is not running (but isRunning=true) because pthread_create() // *just* failed, and Create() hasn't yet set isRunning back to false. // 2) The thread is running (but isRunning=false) because Exit() has been // called but pthread_exit() has not finished executing. bool isRunning; }; #endif