TrinityCore
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
GMutex.h
Go to the documentation of this file.
1 
8 #ifndef G3D_GMutex_h
9 #define G3D_GMutex_h
10 
11 #include "G3D/platform.h"
12 #include "G3D/AtomicInt32.h"
13 #include "G3D/debugAssert.h"
14 #include <string>
15 
16 #ifndef G3D_WINDOWS
17 # include <pthread.h>
18 # include <signal.h>
19 #endif
20 
21 #if defined(G3D_LINUX) || defined(G3D_OSX)
22 # include <unistd.h> // For usleep
23 #endif
24 
25 
26 namespace G3D {
27 
36 class Spinlock {
37 private:
38 
40 
41 public:
42 
43  inline Spinlock() : x(0) {}
44 
52  inline bool lock() {
53  bool first = true;
54  while (x.compareAndSet(0, 1) == 1) {
55  first = false;
56 # ifdef G3D_WINDOWS
57  Sleep(0);
58 # else
59  usleep(0);
60 # endif
61  }
62  return first;
63  }
64 
65  inline void unlock() {
66  x.compareAndSet(1, 0);
67  }
68 
69 };
70 
76 class GMutex {
77 private:
78 # ifdef G3D_WINDOWS
79  CRITICAL_SECTION m_handle;
80 # else
81  pthread_mutex_t m_handle;
82  pthread_mutexattr_t m_attr;
83 # endif
84 
85  // Not implemented on purpose, don't use
86  GMutex(const GMutex &mlock);
87  GMutex &operator=(const GMutex &);
88  bool operator==(const GMutex&);
89 
90 public:
91  GMutex();
92  ~GMutex();
93 
95  void lock();
96 
99  bool tryLock();
100 
102  void unlock();
103 };
104 
105 
109 class GMutexLock {
110 private:
112 
113  // Not implemented on purpose, don't use
114  GMutexLock(const GMutexLock &mlock);
115  GMutexLock &operator=(const GMutexLock &);
116  bool operator==(const GMutexLock&);
117 
118 public:
119  GMutexLock(GMutex* mutex) {
120  m = mutex;
121  m->lock();
122  }
123 
125  m->unlock();
126  }
127 };
128 
129 } // G3D
130 
131 #endif
GMutex * m
Definition: GMutex.h:111
void lock()
Definition: GThread.cpp:248
Mutual exclusion lock used for synchronization.
Definition: GMutex.h:76
bool lock()
Definition: GMutex.h:52
Definition: AABox.h:25
Definition: AtomicInt32.h:29
GMutexLock(GMutex *mutex)
Definition: GMutex.h:119
~GMutex()
Definition: GThread.cpp:228
GMutex()
Definition: GThread.cpp:215
GMutex & operator=(const GMutex &)
bool tryLock()
Definition: GThread.cpp:240
void unlock()
Definition: GThread.cpp:256
Spinlock()
Definition: GMutex.h:43
AtomicInt32 x
Definition: GMutex.h:39
void unlock()
Definition: GMutex.h:65
GMutexLock & operator=(const GMutexLock &)
A mutual exclusion lock that busy-waits when locking.
Definition: GMutex.h:36
pthread_mutexattr_t m_attr
Definition: GMutex.h:82
GMutexLock(const GMutexLock &mlock)
int32 compareAndSet(const int32 comperand, const int32 exchange)
Definition: AtomicInt32.h:142
pthread_mutex_t m_handle
Definition: GMutex.h:81
bool operator==(const GMutexLock &)
Definition: GMutex.h:109
~GMutexLock()
Definition: GMutex.h:124
bool operator==(const GMutex &)