00001 #ifndef KOLTHREAD_H_INCLUDED 00002 #define KOLTHREAD_H_INCLUDED 00003 00004 /* Note on Windows 00005 * <winsock2.h> is used instead of <windows.h> because 00006 * that the <windows.h> includes the <winsock.h> if 00007 * <winsock2.h> is not included. 00008 */ 00009 #ifdef WIN32 00010 #include <winsock2.h> 00011 #include <process.h> 00012 #define SEM_VALUE_MAX (2147483647) 00013 #else 00014 #include <pthread.h> 00015 #include <semaphore.h> 00016 #include <signal.h> 00017 #endif /* WIN32 */ 00018 00019 namespace kekonline 00020 { 00021 #ifdef WIN32 00022 typedef HANDLE mutex_t; 00023 typedef HANDLE thread_t; 00024 typedef HANDLE sem_t; 00025 #else 00026 typedef pthread_mutex_t mutex_t; 00027 typedef pthread_t thread_t; 00028 #endif /* WIN32 */ 00029 00030 class Mutex 00031 { 00032 public: 00033 Mutex(); 00034 virtual ~Mutex(); 00035 virtual int lock(); 00036 virtual int trylock(); 00037 virtual int unlock(); 00038 00039 protected: 00040 mutex_t m_mutex; 00041 }; 00042 00043 class Semaphore 00044 { 00045 public: 00046 Semaphore(unsigned int value); 00047 virtual ~Semaphore(); 00048 int wait(); 00049 int trywait(); 00050 int post(); 00051 00052 protected: 00053 sem_t m_sem; 00054 }; 00055 00056 class ThreadController; 00057 class Thread 00058 { 00059 private: 00060 #ifdef WIN32 00061 static unsigned int __stdcall start_routine(void *); 00062 #else 00063 static void* start_routine(void *); 00064 #endif 00065 00066 public: 00067 static void millisleep(unsigned long msec); 00068 00069 public: 00070 Thread(); 00071 virtual ~Thread(); 00072 virtual int start(); 00073 virtual int join(); 00074 virtual int cancel(); 00075 void controller(ThreadController* pctrl); 00076 ThreadController* controller() const; 00077 void delthreadid(thread_t t); 00078 thread_t delthreadid() const; 00079 00080 protected: 00081 virtual int run(); 00082 00083 protected: 00084 ThreadController* m_controller; 00085 thread_t m_threadid; 00086 thread_t m_delthreadid; 00087 }; 00088 00089 class ThreadController 00090 { 00091 private: 00092 #ifdef WIN32 00093 static unsigned int __stdcall ctrl_routine(void *); 00094 #else 00095 static void* ctrl_routine(void *); 00096 #endif 00097 00098 public: 00099 ThreadController(); 00100 virtual ~ThreadController(); 00101 bool post(Thread* p); 00102 bool done(Thread* p); 00103 int lock(); 00104 int unlock(); 00105 int join(); 00106 int numrunning(); 00107 void delthread(Thread* p); 00108 00109 private: 00110 void closeid(); 00111 00112 private: 00113 int m_running; 00114 thread_t m_threadid; 00115 Mutex m_mutex; 00116 }; 00117 } 00118 #endif 00119
1.4.6-20060327