00001 #ifndef MT_THREAD_H 00002 #define MT_THREAD_H 00003 00004 #include <memory.h> 00005 00006 #include "base.h" 00007 00008 #include <pthread.h> 00009 #include <signal.h> 00010 00011 namespace mt 00012 { 00013 00014 class thread 00015 { 00016 MT_PREVENT_COPY(thread) 00017 00018 public: 00019 00020 typedef thread this_type; 00021 typedef void base_type; 00022 00023 thread(void) : flags(0) 00024 { 00025 ; 00026 } 00027 00028 virtual ~thread(void) 00029 { 00030 ; 00031 } 00032 00033 virtual bool start(void) 00034 { 00035 if ((this->flags & thread_started) != 0) return false; 00036 00037 pthread_create(&(this->tid), 0, this_type::thread_func, reinterpret_cast<void *>(this)); 00038 00039 /* 00040 sched_param sp; 00041 memset(&sp, 0, sizeof(sched_param)); 00042 sp.sched_priority = sched_get_priority_min(SCHED_OTHER); 00043 sp.sched_priority = 0; // normal 00044 pthread_setschedparam(this->tid, SCHED_OTHER, &sp); 00045 */ 00046 00047 this->flags |= thread_started; 00048 00049 return true; 00050 } 00051 00052 virtual bool wait(void) 00053 { 00054 if ((this->flags & thread_started) == 0) return false; 00055 pthread_join(this->tid, 0); 00056 this->flags &= ~thread_started; 00057 return true; 00058 } 00059 00060 virtual bool kill(void) 00061 { 00062 if ((this->flags & thread_started) == 0) return false; 00063 pthread_kill(this->tid, 0); 00064 this->flags &= ~(thread_started | thread_running); 00065 return true; 00066 } 00067 00068 bool is_started(void) const 00069 { 00070 return ((this->flags & thread_started) != 0); 00071 } 00072 00073 bool is_running(void) const 00074 { 00075 return ((this->flags & thread_running) != 0); 00076 } 00077 00078 protected: 00079 00080 virtual void run(void) 00081 { 00082 ; 00083 } 00084 00085 private: 00086 00087 enum thread_flags 00088 { 00089 thread_none = ( 0), 00090 thread_started = (1 << 0), 00091 thread_running = (1 << 1) 00092 }; 00093 00094 volatile unsigned int flags; 00095 pthread_t tid; 00096 00097 static void * thread_func(void * param) 00098 { 00099 this_type * p_this = reinterpret_cast<this_type *>(param); 00100 MT_ASSERT(p_this != 0); 00101 00102 p_this->flags |= thread_running; 00103 p_this->run(); 00104 p_this->flags &= ~thread_running; 00105 00106 return 0; 00107 } 00108 }; 00109 00110 } 00111 00112 #endif // MT_THREAD_H