1 // Copyright (c) 2007, Google Inc. 2 // All rights reserved. 3 // 4 // Redistribution and use in source and binary forms, with or without 5 // modification, are permitted provided that the following conditions are 6 // met: 7 // 8 // * Redistributions of source code must retain the above copyright 9 // notice, this list of conditions and the following disclaimer. 10 // * Redistributions in binary form must reproduce the above 11 // copyright notice, this list of conditions and the following disclaimer 12 // in the documentation and/or other materials provided with the 13 // distribution. 14 // * Neither the name of Google Inc. nor the names of its 15 // contributors may be used to endorse or promote products derived from 16 // this software without specific prior written permission. 17 // 18 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 19 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 20 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 21 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 22 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 23 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 24 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 25 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 26 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 27 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 // 30 // --- 31 // Author: Craig Silverstein. 32 // 33 // A simple mutex wrapper, supporting locks and read-write locks. 34 // You should assume the locks are *not* re-entrant. 35 // 36 // To use: you should define the following macros in your configure.ac: 37 // ACX_PTHREAD 38 // AC_RWLOCK 39 // The latter is defined in ../autoconf. 40 // 41 // This class is meant to be internal-only and should be wrapped by an 42 // internal namespace. Before you use this module, please give the 43 // name of your internal namespace for this module. Or, if you want 44 // to expose it, you'll want to move it to the Google namespace. We 45 // cannot put this class in global namespace because there can be some 46 // problems when we have multiple versions of Mutex in each shared object. 47 // 48 // NOTE: TryLock() is broken for NO_THREADS mode, at least in NDEBUG 49 // mode. 50 // 51 // CYGWIN NOTE: Cygwin support for rwlock seems to be buggy: 52 // http://www.cygwin.com/ml/cygwin/2008-12/msg00017.html 53 // Because of that, we might as well use windows locks for 54 // cygwin. They seem to be more reliable than the cygwin pthreads layer. 55 // 56 // TRICKY IMPLEMENTATION NOTE: 57 // This class is designed to be safe to use during 58 // dynamic-initialization -- that is, by global constructors that are 59 // run before main() starts. The issue in this case is that 60 // dynamic-initialization happens in an unpredictable order, and it 61 // could be that someone else's dynamic initializer could call a 62 // function that tries to acquire this mutex -- but that all happens 63 // before this mutex's constructor has run. (This can happen even if 64 // the mutex and the function that uses the mutex are in the same .cc 65 // file.) Basically, because Mutex does non-trivial work in its 66 // constructor, it's not, in the naive implementation, safe to use 67 // before dynamic initialization has run on it. 68 // 69 // The solution used here is to pair the actual mutex primitive with a 70 // bool that is set to true when the mutex is dynamically initialized. 71 // (Before that it's false.) Then we modify all mutex routines to 72 // look at the bool, and not try to lock/unlock until the bool makes 73 // it to true (which happens after the Mutex constructor has run.) 74 // 75 // This works because before main() starts -- particularly, during 76 // dynamic initialization -- there are no threads, so a) it's ok that 77 // the mutex operations are a no-op, since we don't need locking then 78 // anyway; and b) we can be quite confident our bool won't change 79 // state between a call to Lock() and a call to Unlock() (that would 80 // require a global constructor in one translation unit to call Lock() 81 // and another global constructor in another translation unit to call 82 // Unlock() later, which is pretty perverse). 83 // 84 // That said, it's tricky, and can conceivably fail; it's safest to 85 // avoid trying to acquire a mutex in a global constructor, if you 86 // can. One way it can fail is that a really smart compiler might 87 // initialize the bool to true at static-initialization time (too 88 // early) rather than at dynamic-initialization time. To discourage 89 // that, we set is_safe_ to true in code (not the constructor 90 // colon-initializer) and set it to true via a function that always 91 // evaluates to true, but that the compiler can't know always 92 // evaluates to true. This should be good enough. 93 // 94 // A related issue is code that could try to access the mutex 95 // after it's been destroyed in the global destructors (because 96 // the Mutex global destructor runs before some other global 97 // destructor, that tries to acquire the mutex). The way we 98 // deal with this is by taking a constructor arg that global 99 // mutexes should pass in, that causes the destructor to do no 100 // work. We still depend on the compiler not doing anything 101 // weird to a Mutex's memory after it is destroyed, but for a 102 // static global variable, that's pretty safe. 103 104 #ifndef GOOGLE_MUTEX_H_ 105 #define GOOGLE_MUTEX_H_ 106 107 #include <config.h> 108 109 #if defined(NO_THREADS) 110 typedef int MutexType; // to keep a lock-count 111 #elif defined(_WIN32) || defined(__CYGWIN__) || defined(__CYGWIN32__) 112 # ifndef WIN32_LEAN_AND_MEAN 113 # define WIN32_LEAN_AND_MEAN // We only need minimal includes 114 # endif 115 // We need Windows NT or later for TryEnterCriticalSection(). If you 116 // don't need that functionality, you can remove these _WIN32_WINNT 117 // lines, and change TryLock() to assert(0) or something. 118 # ifndef _WIN32_WINNT 119 # define _WIN32_WINNT 0x0400 120 # endif 121 # include <windows.h> 122 typedef CRITICAL_SECTION MutexType; 123 #elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) 124 // Needed for pthread_rwlock_*. If it causes problems, you could take it 125 // out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it 126 // *does* cause problems for FreeBSD, or MacOSX, but isn't needed 127 // for locking there.) 128 # ifdef __linux__ 129 # define _XOPEN_SOURCE 500 // may be needed to get the rwlock calls 130 # endif 131 # include <pthread.h> 132 typedef pthread_rwlock_t MutexType; 133 #elif defined(HAVE_PTHREAD) 134 # include <pthread.h> 135 typedef pthread_mutex_t MutexType; 136 #else 137 # error Need to implement mutex.h for your architecture, or #define NO_THREADS 138 #endif 139 140 #include <assert.h> 141 #include <stdlib.h> // for abort() 142 143 #define MUTEX_NAMESPACE perftools_mutex_namespace 144 145 namespace MUTEX_NAMESPACE { 146 147 class Mutex { 148 public: 149 // This is used for the single-arg constructor 150 enum LinkerInitialized { LINKER_INITIALIZED }; 151 152 // Create a Mutex that is not held by anybody. This constructor is 153 // typically used for Mutexes allocated on the heap or the stack. 154 inline Mutex(); 155 // This constructor should be used for global, static Mutex objects. 156 // It inhibits work being done by the destructor, which makes it 157 // safer for code that tries to acqiure this mutex in their global 158 // destructor. 159 inline Mutex(LinkerInitialized); 160 161 // Destructor 162 inline ~Mutex(); 163 164 inline void Lock(); // Block if needed until free then acquire exclusively 165 inline void Unlock(); // Release a lock acquired via Lock() 166 inline bool TryLock(); // If free, Lock() and return true, else return false 167 // Note that on systems that don't support read-write locks, these may 168 // be implemented as synonyms to Lock() and Unlock(). So you can use 169 // these for efficiency, but don't use them anyplace where being able 170 // to do shared reads is necessary to avoid deadlock. 171 inline void ReaderLock(); // Block until free or shared then acquire a share 172 inline void ReaderUnlock(); // Release a read share of this Mutex 173 inline void WriterLock() { Lock(); } // Acquire an exclusive lock 174 inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock() 175 176 private: 177 MutexType mutex_; 178 // We want to make sure that the compiler sets is_safe_ to true only 179 // when we tell it to, and never makes assumptions is_safe_ is 180 // always true. volatile is the most reliable way to do that. 181 volatile bool is_safe_; 182 // This indicates which constructor was called. 183 bool destroy_; 184 185 inline void SetIsSafe() { is_safe_ = true; } 186 187 // Catch the error of writing Mutex when intending MutexLock. 188 Mutex(Mutex* /*ignored*/) {} 189 // Disallow "evil" constructors 190 Mutex(const Mutex&); 191 void operator=(const Mutex&); 192 }; 193 194 // Now the implementation of Mutex for various systems 195 #if defined(NO_THREADS) 196 197 // When we don't have threads, we can be either reading or writing, 198 // but not both. We can have lots of readers at once (in no-threads 199 // mode, that's most likely to happen in recursive function calls), 200 // but only one writer. We represent this by having mutex_ be -1 when 201 // writing and a number > 0 when reading (and 0 when no lock is held). 202 // 203 // In debug mode, we assert these invariants, while in non-debug mode 204 // we do nothing, for efficiency. That's why everything is in an 205 // assert. 206 207 Mutex::Mutex() : mutex_(0) { } 208 Mutex::Mutex(Mutex::LinkerInitialized) : mutex_(0) { } 209 Mutex::~Mutex() { assert(mutex_ == 0); } 210 void Mutex::Lock() { assert(--mutex_ == -1); } 211 void Mutex::Unlock() { assert(mutex_++ == -1); } 212 bool Mutex::TryLock() { if (mutex_) return false; Lock(); return true; } 213 void Mutex::ReaderLock() { assert(++mutex_ > 0); } 214 void Mutex::ReaderUnlock() { assert(mutex_-- > 0); } 215 216 #elif defined(_WIN32) || defined(__CYGWIN__) || defined(__CYGWIN32__) 217 218 Mutex::Mutex() : destroy_(true) { 219 InitializeCriticalSection(&mutex_); 220 SetIsSafe(); 221 } 222 Mutex::Mutex(LinkerInitialized) : destroy_(false) { 223 InitializeCriticalSection(&mutex_); 224 SetIsSafe(); 225 } 226 Mutex::~Mutex() { if (destroy_) DeleteCriticalSection(&mutex_); } 227 void Mutex::Lock() { if (is_safe_) EnterCriticalSection(&mutex_); } 228 void Mutex::Unlock() { if (is_safe_) LeaveCriticalSection(&mutex_); } 229 bool Mutex::TryLock() { return is_safe_ ? 230 TryEnterCriticalSection(&mutex_) != 0 : true; } 231 void Mutex::ReaderLock() { Lock(); } // we don't have read-write locks 232 void Mutex::ReaderUnlock() { Unlock(); } 233 234 #elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK) 235 236 #define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \ 237 if (is_safe_ && fncall(&mutex_) != 0) abort(); \ 238 } while (0) 239 240 Mutex::Mutex() : destroy_(true) { 241 SetIsSafe(); 242 if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort(); 243 } 244 Mutex::Mutex(Mutex::LinkerInitialized) : destroy_(false) { 245 SetIsSafe(); 246 if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort(); 247 } 248 Mutex::~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_rwlock_destroy); } 249 void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); } 250 void Mutex::Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } 251 bool Mutex::TryLock() { return is_safe_ ? 252 pthread_rwlock_trywrlock(&mutex_) == 0 : true; } 253 void Mutex::ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock); } 254 void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); } 255 #undef SAFE_PTHREAD 256 257 #elif defined(HAVE_PTHREAD) 258 259 #define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \ 260 if (is_safe_ && fncall(&mutex_) != 0) abort(); \ 261 } while (0) 262 263 Mutex::Mutex() : destroy_(true) { 264 SetIsSafe(); 265 if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort(); 266 } 267 Mutex::Mutex(Mutex::LinkerInitialized) : destroy_(false) { 268 SetIsSafe(); 269 if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort(); 270 } 271 Mutex::~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_mutex_destroy); } 272 void Mutex::Lock() { SAFE_PTHREAD(pthread_mutex_lock); } 273 void Mutex::Unlock() { SAFE_PTHREAD(pthread_mutex_unlock); } 274 bool Mutex::TryLock() { return is_safe_ ? 275 pthread_mutex_trylock(&mutex_) == 0 : true; } 276 void Mutex::ReaderLock() { Lock(); } 277 void Mutex::ReaderUnlock() { Unlock(); } 278 #undef SAFE_PTHREAD 279 280 #endif 281 282 // -------------------------------------------------------------------------- 283 // Some helper classes 284 285 // MutexLock(mu) acquires mu when constructed and releases it when destroyed. 286 class MutexLock { 287 public: 288 explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); } 289 ~MutexLock() { mu_->Unlock(); } 290 private: 291 Mutex * const mu_; 292 // Disallow "evil" constructors 293 MutexLock(const MutexLock&); 294 void operator=(const MutexLock&); 295 }; 296 297 // ReaderMutexLock and WriterMutexLock do the same, for rwlocks 298 class ReaderMutexLock { 299 public: 300 explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); } 301 ~ReaderMutexLock() { mu_->ReaderUnlock(); } 302 private: 303 Mutex * const mu_; 304 // Disallow "evil" constructors 305 ReaderMutexLock(const ReaderMutexLock&); 306 void operator=(const ReaderMutexLock&); 307 }; 308 309 class WriterMutexLock { 310 public: 311 explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); } 312 ~WriterMutexLock() { mu_->WriterUnlock(); } 313 private: 314 Mutex * const mu_; 315 // Disallow "evil" constructors 316 WriterMutexLock(const WriterMutexLock&); 317 void operator=(const WriterMutexLock&); 318 }; 319 320 // Catch bug where variable name is omitted, e.g. MutexLock (&mu); 321 #define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_decl_missing_var_name) 322 #define ReaderMutexLock(x) COMPILE_ASSERT(0, rmutex_lock_decl_missing_var_name) 323 #define WriterMutexLock(x) COMPILE_ASSERT(0, wmutex_lock_decl_missing_var_name) 324 325 } // namespace MUTEX_NAMESPACE 326 327 using namespace MUTEX_NAMESPACE; 328 329 #undef MUTEX_NAMESPACE 330 331 #endif /* #define GOOGLE_SIMPLE_MUTEX_H_ */ 332