Thread.h++
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 #ifndef __ccxx_Thread_hxx
00024 #define __ccxx_Thread_hxx
00025
00026 #include <commonc++/Common.h++>
00027 #include <commonc++/AtomicCounter.h++>
00028 #include <commonc++/Runnable.h++>
00029 #include <commonc++/String.h++>
00030 #include <commonc++/ThreadLocal.h++>
00031
00032 #ifdef CCXX_OS_POSIX
00033 #include <pthread.h>
00034 #endif
00035
00036 namespace ccxx {
00037
00055 class COMMONCPP_API Thread : public Runnable
00056 {
00057 public:
00058
00066 Thread(bool detached = false, size_t stackSize = 0);
00067
00077 Thread(Runnable *runnable, bool detached = false, size_t stackSize = 0);
00078
00080 virtual ~Thread() throw();
00081
00087 virtual void start() throw();
00088
00093 virtual void stop() throw();
00094
00101 bool join() throw();
00102
00104 bool isRunning() const throw();
00105
00107 inline bool isDetached() const throw()
00108 { return(_detached); }
00109
00111 void setPriority(Priority priority) throw();
00112
00114 Priority getPriority() const throw();
00115
00117 inline void setName(const String& name) throw()
00118 { _name = name; }
00119
00121 inline String getName() const throw()
00122 { return(_name); }
00123
00128 static void sleep(timespan_ms_t msec) throw();
00129
00135 static Thread *currentThread();
00136
00138 static ThreadID currentThreadID() throw();
00139
00140 protected:
00141
00145 virtual void run();
00146
00151 virtual void cleanup();
00152
00160 bool trySleep(timespan_ms_t msec) throw();
00161
00167 bool testCancel() throw();
00168
00170 void yield() throw();
00171
00173 static void exit() throw();
00174
00175 private:
00176
00177 Thread(ThreadHandle id);
00178
00179 AtomicCounter _runFlag;
00180 bool _cancelled;
00181 bool _detached;
00182 size_t _stackSize;
00183 String _name;
00184 #ifdef CCXX_OS_WINDOWS
00185 HANDLE _thread;
00186 HANDLE _cancelEvent;
00187 bool _cleanupDone;
00188 #else
00189 pthread_t _thread;
00190 pthread_attr_t _attrs;
00191 #endif
00192 Runnable *_runnable;
00193
00194 #ifdef CCXX_OS_WINDOWS
00195 static DWORD WINAPI _startupDispatcher(LPVOID arg);
00196 static void _cleanupTLS() throw();
00197 #else
00198 static void *_startupDispatcher(void *arg);
00199 static void _cleanupDispatcher(void *arg);
00200 #endif
00201
00202 void _run() throw();
00203 void _init() throw();
00204
00205 CCXX_COPY_DECLS(Thread);
00206 };
00207
00208 };
00209
00210 #endif // __ccxx_Thread_hxx
00211
00212