00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023 #ifndef LUX_FASTMUTEX_H
00024 #define LUX_FASTMUTEX_H
00025
00026
00027
00028 #if defined(__APPLE__)
00029 #include <libkern/OSAtomic.h>
00030 #elif defined(__WIN32__)
00031 #include <windows.h>
00032 #else
00033 #include <boost/thread/mutex.hpp>
00034 #endif
00035
00036 namespace lux
00037 {
00038 #if defined(__APPLE__)
00039 class fast_mutex
00040 {
00041 private:
00042 OSSpinLock sl_;
00043
00044 fast_mutex(fast_mutex const &);
00045 fast_mutex & operator=(fast_mutex const &);
00046
00047 public:
00048
00049 fast_mutex()
00050 {
00051 sl_ = OS_SPINLOCK_INIT;
00052 }
00053
00054 ~fast_mutex()
00055 {
00056 }
00057
00058 bool try_lock()
00059 {
00060 return OSSpinLockTry(&sl_);
00061 }
00062
00063 void lock()
00064 {
00065 OSSpinLockLock(&sl_);
00066 }
00067
00068 void unlock()
00069 {
00070 OSSpinLockUnlock(&sl_);
00071 }
00072
00073 class scoped_lock;
00074 friend class scoped_lock;
00075
00076 class scoped_lock
00077 {
00078 private:
00079
00080 fast_mutex & m_;
00081 bool has_lock;
00082
00083 scoped_lock(scoped_lock const &);
00084 scoped_lock & operator=(scoped_lock const &);
00085
00086 public:
00087
00088 scoped_lock(fast_mutex & m): m_(m)
00089 {
00090 m_.lock();
00091 has_lock = true;
00092 }
00093
00094 ~scoped_lock()
00095 {
00096 if (has_lock)
00097 m_.unlock();
00098 }
00099
00100 void unlock()
00101 {
00102 if (has_lock)
00103 m_.unlock();
00104 has_lock = false;
00105 }
00106 };
00107 };
00108 #elif defined(WIN32)
00109 class fast_mutex
00110 {
00111 private:
00112
00113 CRITICAL_SECTION cs_;
00114
00115 fast_mutex(fast_mutex const &);
00116 fast_mutex & operator=(fast_mutex const &);
00117
00118 public:
00119
00120 fast_mutex()
00121 {
00122 InitializeCriticalSection(&cs_);
00123 }
00124
00125 ~fast_mutex()
00126 {
00127 DeleteCriticalSection(&cs_);
00128 }
00129
00130 bool try_lock()
00131 {
00132 return TryEnterCriticalSection(&cs_) == TRUE;
00133 }
00134
00135 void lock()
00136 {
00137 EnterCriticalSection(&cs_);
00138 }
00139
00140 void unlock()
00141 {
00142 LeaveCriticalSection(&cs_);
00143 }
00144
00145 class scoped_lock;
00146 friend class scoped_lock;
00147
00148 class scoped_lock
00149 {
00150 private:
00151
00152 fast_mutex & m_;
00153 bool has_lock;
00154
00155 scoped_lock(scoped_lock const &);
00156 scoped_lock & operator=(scoped_lock const &);
00157
00158 public:
00159
00160 scoped_lock(fast_mutex & m): m_(m)
00161 {
00162 m_.lock();
00163 has_lock = true;
00164 }
00165
00166 ~scoped_lock()
00167 {
00168 if (has_lock)
00169 m_.unlock();
00170 }
00171
00172 void unlock()
00173 {
00174 if (has_lock)
00175 m_.unlock();
00176 has_lock = false;
00177 }
00178 };
00179 };
00180 #else
00181 typedef boost::mutex fast_mutex;
00182 #endif
00183
00184 }
00185
00186 #endif // LUX_FASTMUTEX_H