dthread.h
Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031 #if !defined(DTHREAD_H_)
00032 #define DTHREAD_H_
00033
00034 #include <stdlib.h>
00035 #include "util.h"
00036 #include <cassert>
00037
00038 #if !defined(os_windows)
00039 #define cap_pthreads
00040 #include <pthread.h>
00041 #else
00042 #include <common/h/ntheaders.h>
00043 #endif
00044
00045 #if !defined(WINAPI)
00046 #define WINAPI
00047 #endif
00048
00049 class COMMON_EXPORT DThread {
00050 #if defined(cap_pthreads)
00051 pthread_t thrd;
00052 public:
00053 typedef void (*initial_func_t)(void *);
00054 typedef void dthread_ret_t;
00055 #define DTHREAD_RET_VAL
00056 #else
00057 HANDLE thrd;
00058 DWORD tid;
00059 public:
00060 typedef LPTHREAD_START_ROUTINE initial_func_t;
00061 typedef int dthread_ret_t;
00062 #define DTHREAD_RET_VAL 0
00063 #endif
00064 bool live;
00065 public:
00066 DThread();
00067 ~DThread();
00068
00069 static long self();
00070 bool spawn(initial_func_t func, void *param);
00071 bool join();
00072 long id();
00073 };
00074
00075 class COMMON_EXPORT Mutex {
00076 friend class CondVar;
00077 #if defined(cap_pthreads)
00078 pthread_mutex_t mutex;
00079 #else
00080 #if defined(os_windows)
00081 HANDLE mutex;
00082 #endif
00083 #endif
00084 public:
00085 Mutex(bool recursive=false);
00086 ~Mutex();
00087
00088 bool trylock();
00089 bool lock();
00090 bool unlock();
00091 };
00092
00093 class COMMON_EXPORT CondVar {
00094 #if defined(cap_pthreads)
00095 pthread_cond_t cond;
00096 #else
00097 int numWaiting;
00098 CRITICAL_SECTION numWaitingLock;
00099 HANDLE wait_sema;
00100 HANDLE wait_done;
00101 bool was_broadcast;
00102 Mutex sync_cv_ops;
00103 #endif
00104 Mutex *mutex;
00105 bool created_mutex;
00106 public:
00107 CondVar(Mutex *m = NULL);
00108 ~CondVar();
00109
00110 bool unlock();
00111 bool trylock();
00112 bool lock();
00113 bool signal();
00114 bool broadcast();
00115 bool wait();
00116 };
00117
00118
00119
00120
00121
00122
00123 class ScopeLock {
00124 private:
00125 Mutex *m;
00126 CondVar *c;
00127 public:
00128 ScopeLock(Mutex &m_) :
00129 m(&m_),
00130 c(NULL)
00131 {
00132 bool result = m->lock();
00133 assert(result);
00134 }
00135
00136 ScopeLock(CondVar &c_) :
00137 m(NULL),
00138 c(&c_)
00139 {
00140 bool result = c->lock();
00141 assert(result);
00142 }
00143
00144 void unlock() {
00145 if (m) {
00146 m->unlock();
00147 m = NULL;
00148 }
00149 else if (c) {
00150 c->unlock();
00151 c = NULL;
00152 }
00153 }
00154
00155 bool isLocked() {
00156 return m || c;
00157 }
00158
00159 ~ScopeLock() {
00160 unlock();
00161 }
00162 };
00163
00164 #endif