00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00021 #ifndef __DERS__THREAD_HPP__
00022 #define __DERS__THREAD_HPP__
00023
00024 #include <ders/config.hpp>
00025 #include <ders/sh_ptr.hpp>
00026
00027 namespace ders {
00028
00032 class thread : virtual public destroyable {
00033 public:
00034 virtual bool is_running()=0;
00035 virtual void join()=0;
00036 };
00037
00038 typedef sh_ptr<thread> sh_thread;
00039
00047 sh_thread new_thread(mem_pool& mp, void (*start)(void*), void* arg);
00048
00052 class mutex : virtual public destroyable {
00053 public:
00054 virtual void lock()=0;
00055 virtual void unlock()=0;
00056 };
00057
00058 typedef sh_ptr<mutex> sh_mutex;
00059
00065 sh_mutex new_mutex(mem_pool& mp);
00066
00072 sh_mutex new_long_mutex(mem_pool& mp);
00073
00077 class auto_mutex {
00078 mutex& mtx;
00079
00080 auto_mutex(const auto_mutex&);
00081 auto_mutex& operator=(const auto_mutex&);
00082
00083 public:
00084 auto_mutex(mutex& m) : mtx(m) { mtx.lock(); }
00085 ~auto_mutex() { mtx.unlock(); }
00086 };
00087
00091 class cond_var : virtual public destroyable {
00092 public:
00093 static const long infinite=-1;
00094
00095 void wait() { wait(infinite); }
00096 virtual void wait(long timeout)=0;
00097 virtual void notify()=0;
00098 virtual void notify_all()=0;
00099 };
00100
00101 typedef sh_ptr<cond_var> sh_cond_var;
00102
00109 sh_cond_var new_cond_var(mem_pool& mp, mutex& mtx);
00110
00111 class barrier;
00112
00116 class barrier_listener : virtual public destroyable {
00117 public:
00119 enum action { release_one_false, release_all_false, release_all_true };
00120
00121 virtual action on_release(barrier& bar)=0;
00122 };
00123
00127 class barrier {
00128 sh_mutex mtx;
00129 sh_cond_var cv1, cv2;
00130 int maxCnt, wtCnt, relCnt;
00131 bool ret;
00132 barrier_listener* blnr;
00133
00134 public:
00135 barrier(mem_pool& mp, int cnt);
00136 ~barrier();
00137
00138 int inc_count();
00139 int dec_count();
00140 int get_count();
00141
00142 bool wait();
00143 void release_one();
00144 void release_all();
00145
00146 barrier_listener* set_listener(barrier_listener* bl);
00147 };
00148
00149 typedef sh_ptr<barrier> sh_barrier;
00150
00157 sh_barrier new_barrier(mem_pool& mp, int cnt);
00158
00159 namespace detail {
00160
00161 struct thr_core {
00162 void (*strt)(void*);
00163 void* arg;
00164
00165 mem_pool ownmp;
00166 sh_mutex mtx;
00167 sh_cond_var cv;
00168 int refs;
00169 bool rng;
00170
00171 thr_core(void (*st)(void*), void* ar);
00172
00173 void inc_refs();
00174 void dec_refs(bool parent);
00175 void clear_rng();
00176 void start();
00177
00178 bool is_running();
00179 void join();
00180 };
00181
00182 struct tc_ptr {
00183 bool parent;
00184 thr_core* ptr;
00185
00186 tc_ptr(bool pr, thr_core* pt) : parent(pr), ptr(pt) { ptr->inc_refs(); }
00187 ~tc_ptr() { ptr->dec_refs(parent); }
00188
00189 thr_core* operator->() { return ptr; }
00190 };
00191
00192 }
00193
00194 }
00195
00196 #endif // __DERS__THREAD_HPP__
00197