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 
105 #ifndef GOOGLE_MUTEX_H_
106 #define GOOGLE_MUTEX_H_
107 
108 #include <config.h>
109 
110 #if defined(NO_THREADS)
111   typedef int MutexType;      // to keep a lock-count
112 #elif defined(_WIN32) || defined(__CYGWIN__) || defined(__CYGWIN32__)
113 # ifndef WIN32_LEAN_AND_MEAN
114 #   define WIN32_LEAN_AND_MEAN  // We only need minimal includes
115 # endif
116   // We need Windows NT or later for TryEnterCriticalSection().  If you
117   // don't need that functionality, you can remove these _WIN32_WINNT
118   // lines, and change TryLock() to assert(0) or something.
119 # ifndef _WIN32_WINNT
120 #   define _WIN32_WINNT 0x0400
121 # endif
122 # include <windows.h>
123   typedef CRITICAL_SECTION MutexType;
124 #elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK)
125   // Needed for pthread_rwlock_*.  If it causes problems, you could take it
126   // out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it
127   // *does* cause problems for FreeBSD, or MacOSX, but isn't needed
128   // for locking there.)
129 # ifdef __linux__
130 #   define _XOPEN_SOURCE 500  // may be needed to get the rwlock calls
131 # endif
132 # include <pthread.h>
133   typedef pthread_rwlock_t MutexType;
134 #elif defined(HAVE_PTHREAD)
135 # include <pthread.h>
136   typedef pthread_mutex_t MutexType;
137 #else
138 # error Need to implement mutex.h for your architecture, or #define NO_THREADS
139 #endif
140 
141 #include <assert.h>
142 #include <stdlib.h>      // for abort()
143 
144 #define MUTEX_NAMESPACE perftools_mutex_namespace
145 
146 namespace MUTEX_NAMESPACE {
147 
148 class Mutex {
149  public:
150   // This is used for the single-arg constructor
151   enum LinkerInitialized { LINKER_INITIALIZED };
152 
153   // Create a Mutex that is not held by anybody.  This constructor is
154   // typically used for Mutexes allocated on the heap or the stack.
155   inline Mutex();
156   // This constructor should be used for global, static Mutex objects.
157   // It inhibits work being done by the destructor, which makes it
158   // safer for code that tries to acqiure this mutex in their global
159   // destructor.
160   inline Mutex(LinkerInitialized);
161 
162   // Destructor
163   inline ~Mutex();
164 
165   inline void Lock();    // Block if needed until free then acquire exclusively
166   inline void Unlock();  // Release a lock acquired via Lock()
167   inline bool TryLock(); // If free, Lock() and return true, else return false
168   // Note that on systems that don't support read-write locks, these may
169   // be implemented as synonyms to Lock() and Unlock().  So you can use
170   // these for efficiency, but don't use them anyplace where being able
171   // to do shared reads is necessary to avoid deadlock.
172   inline void ReaderLock();   // Block until free or shared then acquire a share
173   inline void ReaderUnlock(); // Release a read share of this Mutex
WriterLock()174   inline void WriterLock() { Lock(); }     // Acquire an exclusive lock
WriterUnlock()175   inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock()
176 
177  private:
178   MutexType mutex_;
179   // We want to make sure that the compiler sets is_safe_ to true only
180   // when we tell it to, and never makes assumptions is_safe_ is
181   // always true.  volatile is the most reliable way to do that.
182   volatile bool is_safe_;
183   // This indicates which constructor was called.
184   bool destroy_;
185 
SetIsSafe()186   inline void SetIsSafe() { is_safe_ = true; }
187 
188   // Catch the error of writing Mutex when intending MutexLock.
Mutex(Mutex *)189   Mutex(Mutex* /*ignored*/) {}
190   // Disallow "evil" constructors
191   Mutex(const Mutex&);
192   void operator=(const Mutex&);
193 };
194 
195 // Now the implementation of Mutex for various systems
196 #if defined(NO_THREADS)
197 
198 // When we don't have threads, we can be either reading or writing,
199 // but not both.  We can have lots of readers at once (in no-threads
200 // mode, that's most likely to happen in recursive function calls),
201 // but only one writer.  We represent this by having mutex_ be -1 when
202 // writing and a number > 0 when reading (and 0 when no lock is held).
203 //
204 // In debug mode, we assert these invariants, while in non-debug mode
205 // we do nothing, for efficiency.  That's why everything is in an
206 // assert.
207 
Mutex()208 Mutex::Mutex() : mutex_(0) { }
Mutex(Mutex::LinkerInitialized)209 Mutex::Mutex(Mutex::LinkerInitialized) : mutex_(0) { }
~Mutex()210 Mutex::~Mutex()            { assert(mutex_ == 0); }
Lock()211 void Mutex::Lock()         { assert(--mutex_ == -1); }
Unlock()212 void Mutex::Unlock()       { assert(mutex_++ == -1); }
TryLock()213 bool Mutex::TryLock()      { if (mutex_) return false; Lock(); return true; }
ReaderLock()214 void Mutex::ReaderLock()   { assert(++mutex_ > 0); }
ReaderUnlock()215 void Mutex::ReaderUnlock() { assert(mutex_-- > 0); }
216 
217 #elif defined(_WIN32) || defined(__CYGWIN__) || defined(__CYGWIN32__)
218 
Mutex()219 Mutex::Mutex() : destroy_(true) {
220   InitializeCriticalSection(&mutex_);
221   SetIsSafe();
222 }
Mutex(LinkerInitialized)223 Mutex::Mutex(LinkerInitialized) : destroy_(false) {
224   InitializeCriticalSection(&mutex_);
225   SetIsSafe();
226 }
~Mutex()227 Mutex::~Mutex()            { if (destroy_) DeleteCriticalSection(&mutex_); }
Lock()228 void Mutex::Lock()         { if (is_safe_) EnterCriticalSection(&mutex_); }
Unlock()229 void Mutex::Unlock()       { if (is_safe_) LeaveCriticalSection(&mutex_); }
TryLock()230 bool Mutex::TryLock()      { return is_safe_ ?
231                                  TryEnterCriticalSection(&mutex_) != 0 : true; }
ReaderLock()232 void Mutex::ReaderLock()   { Lock(); }      // we don't have read-write locks
ReaderUnlock()233 void Mutex::ReaderUnlock() { Unlock(); }
234 
235 #elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK)
236 
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()241 Mutex::Mutex() : destroy_(true) {
242   SetIsSafe();
243   if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
244 }
Mutex(Mutex::LinkerInitialized)245 Mutex::Mutex(Mutex::LinkerInitialized) : destroy_(false) {
246   SetIsSafe();
247   if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
248 }
~Mutex()249 Mutex::~Mutex()       { if (destroy_) SAFE_PTHREAD(pthread_rwlock_destroy); }
Lock()250 void Mutex::Lock()         { SAFE_PTHREAD(pthread_rwlock_wrlock); }
Unlock()251 void Mutex::Unlock()       { SAFE_PTHREAD(pthread_rwlock_unlock); }
TryLock()252 bool Mutex::TryLock()      { return is_safe_ ?
253                                pthread_rwlock_trywrlock(&mutex_) == 0 : true; }
ReaderLock()254 void Mutex::ReaderLock()   { SAFE_PTHREAD(pthread_rwlock_rdlock); }
ReaderUnlock()255 void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); }
256 #undef SAFE_PTHREAD
257 
258 #elif defined(HAVE_PTHREAD)
259 
260 #define SAFE_PTHREAD(fncall)  do {   /* run fncall if is_safe_ is true */  \
261   if (is_safe_ && fncall(&mutex_) != 0) abort();                           \
262 } while (0)
263 
Mutex()264 Mutex::Mutex() : destroy_(true) {
265   SetIsSafe();
266   if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
267 }
Mutex(Mutex::LinkerInitialized)268 Mutex::Mutex(Mutex::LinkerInitialized) : destroy_(false) {
269   SetIsSafe();
270   if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
271 }
~Mutex()272 Mutex::~Mutex()       { if (destroy_) SAFE_PTHREAD(pthread_mutex_destroy); }
Lock()273 void Mutex::Lock()         { SAFE_PTHREAD(pthread_mutex_lock); }
Unlock()274 void Mutex::Unlock()       { SAFE_PTHREAD(pthread_mutex_unlock); }
TryLock()275 bool Mutex::TryLock()      { return is_safe_ ?
276                                  pthread_mutex_trylock(&mutex_) == 0 : true; }
ReaderLock()277 void Mutex::ReaderLock()   { Lock(); }
ReaderUnlock()278 void Mutex::ReaderUnlock() { Unlock(); }
279 #undef SAFE_PTHREAD
280 
281 #endif
282 
283 // --------------------------------------------------------------------------
284 // Some helper classes
285 
286 // MutexLock(mu) acquires mu when constructed and releases it when destroyed.
287 class MutexLock {
288  public:
MutexLock(Mutex * mu)289   explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); }
~MutexLock()290   ~MutexLock() { mu_->Unlock(); }
291  private:
292   Mutex * const mu_;
293   // Disallow "evil" constructors
294   MutexLock(const MutexLock&);
295   void operator=(const MutexLock&);
296 };
297 
298 // ReaderMutexLock and WriterMutexLock do the same, for rwlocks
299 class ReaderMutexLock {
300  public:
ReaderMutexLock(Mutex * mu)301   explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); }
~ReaderMutexLock()302   ~ReaderMutexLock() { mu_->ReaderUnlock(); }
303  private:
304   Mutex * const mu_;
305   // Disallow "evil" constructors
306   ReaderMutexLock(const ReaderMutexLock&);
307   void operator=(const ReaderMutexLock&);
308 };
309 
310 class WriterMutexLock {
311  public:
WriterMutexLock(Mutex * mu)312   explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); }
~WriterMutexLock()313   ~WriterMutexLock() { mu_->WriterUnlock(); }
314  private:
315   Mutex * const mu_;
316   // Disallow "evil" constructors
317   WriterMutexLock(const WriterMutexLock&);
318   void operator=(const WriterMutexLock&);
319 };
320 
321 // Catch bug where variable name is omitted, e.g. MutexLock (&mu);
322 #define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_decl_missing_var_name)
323 #define ReaderMutexLock(x) COMPILE_ASSERT(0, rmutex_lock_decl_missing_var_name)
324 #define WriterMutexLock(x) COMPILE_ASSERT(0, wmutex_lock_decl_missing_var_name)
325 
326 }  // namespace MUTEX_NAMESPACE
327 
328 using namespace MUTEX_NAMESPACE;
329 
330 #undef MUTEX_NAMESPACE
331 
332 #endif  /* #define GOOGLE_SIMPLE_MUTEX_H_ */
333