00001 /* -*- mode: c++ -*- */ 00002 #ifndef __DAQpp_thread_h__ 00003 #define __DAQpp_thread_h__ 00004 00005 #include <string> 00006 #include <pthread.h> 00007 #include <semaphore.h> 00008 00009 namespace DAQpp 00010 { 00011 00015 class Mutex 00016 { 00017 protected: 00019 bool debug; 00020 00022 pthread_mutex_t _mtx; 00023 00025 pthread_t _owner; 00026 00028 int _count; 00029 public: 00031 Mutex(); 00033 ~Mutex(); 00034 00036 void set_debug(bool x) 00037 { 00038 debug = x; 00039 } 00040 00042 int acquire(); 00046 bool busy(); 00054 int release(); 00055 00056 }; 00057 00069 class Condition : public Mutex 00070 { 00071 private: 00073 pthread_cond_t _cond; 00074 public: 00076 Condition(); 00077 00079 virtual ~Condition(); 00080 00081 00085 bool wait(int timeout = -1); 00086 00088 void notify(); 00089 00091 void notify_all(); 00092 00097 virtual bool condition() = 0; 00102 virtual void exec() 00103 {} 00104 00105 }; 00106 00109 class Semaphore 00110 { 00111 private: 00113 sem_t _sem; 00114 public: 00116 Semaphore(int ifirst); 00118 ~Semaphore(); 00119 00131 int wait(bool block = true); 00132 00134 void post(); 00135 00137 int count(); 00138 }; 00139 00148 class Thread 00149 { 00150 private: 00152 pthread_t _thread; 00153 00155 bool _started; 00156 00158 bool _stopped; 00159 00161 int _nice; 00162 public: 00163 enum CancelType { 00164 deferred, 00165 asynchronous, 00166 disable 00167 }; 00168 00170 Thread(); 00171 00173 virtual ~Thread() 00174 {}; 00175 00177 void nice(int x) 00178 { 00179 _nice = x; 00180 } 00181 00183 void test_cancel(); 00184 00187 void set_cancel(CancelType); 00188 00190 void exit(int v = 0); 00191 00193 virtual void start(); 00194 00196 virtual void stop(); 00197 00199 virtual void run() = 0; 00200 00202 static void *_run(void *); 00203 00205 bool is_running() 00206 { 00207 return _started; 00208 } 00209 00211 bool is_stopped() 00212 { 00213 return _stopped; 00214 } 00215 00216 }; 00217 00218 } 00219 #endif