simple_mutex.h 14 KB

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