00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029 #if !defined(PT_SYSTEM_THREAD_H)
00030 #define PT_SYSTEM_THREAD_H
00031
00032 #include <cxxtools/noncopyable.h>
00033 #include <cxxtools/callable.h>
00034 #include <cxxtools/function.h>
00035 #include <cxxtools/method.h>
00036
00037 namespace cxxtools {
00038
00060 class Thread : protected NonCopyable
00061 {
00062 public:
00064 enum State
00065 {
00066 Ready = 0,
00067 Running = 1,
00068 Finished = 2
00069 };
00070
00071 protected:
00078 Thread();
00079
00086 explicit Thread(const Callable<void>& cb);
00087
00093 void init(const Callable<void>& cb);
00094
00095 public:
00101 virtual ~Thread();
00102
00104 State state() const
00105 { return _state; }
00106
00112 void start();
00113
00114 void create()
00115 { this->start(); }
00116
00123 static void exit();
00124
00131 static void yield();
00132
00138 static void sleep(unsigned int ms);
00139
00140 protected:
00142 void detach();
00143
00145 void join();
00146
00148 bool joinNoThrow();
00149
00151 void terminate();
00152
00153 private:
00155 Thread::State _state;
00156
00158 class ThreadImpl* _impl;
00159 };
00160
00197 class AttachedThread : public Thread
00198 {
00199 public:
00206 explicit AttachedThread(const Callable<void>& cb)
00207 : Thread(cb)
00208 {}
00209
00211 ~AttachedThread()
00212 {
00213 Thread::joinNoThrow();
00214 }
00215
00221 void join()
00222 {
00223 Thread::join();
00224 }
00225
00230 void terminate()
00231 {
00232 Thread::terminate();
00233 }
00234 };
00235
00268 class DetachedThread : public Thread
00269 {
00270 typedef void (*FuncPtrT)();
00271
00272 public:
00273 explicit DetachedThread(FuncPtrT fp)
00274 : Thread( callable(fp) )
00275 {
00276 Thread::detach();
00277 }
00278
00279 protected:
00288 DetachedThread()
00289 : Thread()
00290 {
00291 Thread::init( callable(*this, &DetachedThread::exec) );
00292 Thread::detach();
00293 }
00294
00300 virtual void destroy()
00301 { delete this; }
00302
00308 virtual void run()
00309 {}
00310
00311 private:
00313 void exec()
00314 {
00315 this->run();
00316 this->destroy();
00317 }
00318 };
00319
00320 }
00321
00322 #endif // namespace cxxtools