00001 #ifndef N2NC_SYNCTHREAD_H
00002 #define N2NC_SYNCTHREAD_H
00003
00004 #include "nixsys.h"
00005 #include "mutex.h"
00006
00007 namespace n2nc {
00008 namespace sync {
00009
00015 class Thread{
00016
00017 public:
00018
00020 int run(void *args);
00022 int wait(void **retval);
00024 void* getRetVal();
00026 int terminate();
00028 int getID();
00030 bool isEquals(Thread *t);
00032 std::string toString();
00033
00034 void setName(std::string name);
00035
00036 static bool compare(Thread &t1, Thread &t2);
00037
00038 static bool init();
00039 static Thread& getCurrent();
00040
00041 protected:
00042 Thread();
00043 ~Thread();
00044
00046 virtual int pre_start();
00048 virtual void* entry_point()=0 ;
00051 virtual int exit_point();
00052
00053 void *m_args ;
00054 void *m_ret_args ;
00055 pthread_t m_thread ;
00056 private:
00058 static void* _start(Thread* caller);
00059
00060 bool m_isstarted ;
00061 bool m_isrunning ;
00062 bool m_iscancelled ;
00064 std::string m_name ;
00065
00066 static std::map<pthread_t,Thread*> m_runthreads ;
00067 static n2nc::sync::Mutex m_maplock ;
00068
00073 };
00074
00083 class MainThread : public Thread {
00084 private:
00085 MainThread() : Thread() {
00086
00087 this->pre_start();
00088 this->setName("Main");
00089 }
00090 ~MainThread(){}
00091 virtual void* entry_point(){}
00092
00093
00094
00095
00096
00097 friend class Thread ;
00098
00099 };
00100
00107 class InlineThread : public Thread {
00108 public:
00110 typedef void *(*m_start_routine)(void*) ;
00111 typedef int (*m_stop_routine)(void*) ;
00113 InlineThread(m_start_routine fnc,m_stop_routine fncstop = NULL) : Thread() {
00114 this->m_runfnc = fnc ;
00115 this->m_stopfnc = fncstop ;
00116 }
00117 ~InlineThread(){}
00118 private:
00119 virtual void* entry_point(){
00120 return this->m_runfnc(this->m_args);
00121 }
00122 virtual int exit_point(){
00123 if ( this->m_stopfnc == NULL ) return 0 ;
00124 return this->m_stopfnc(this->m_ret_args);
00125 }
00126
00127 m_start_routine m_runfnc ;
00128 m_stop_routine m_stopfnc ;
00129 };
00130
00131 }
00132 }
00133
00134 #endif