• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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, so it's defined in the
42 // global namespace.  If you want to expose it, you'll want to move
43 // it to the Google namespace.
44 //
45 // NOTE: by default, we have #ifdef'ed out the TryLock() method.
46 //       This is for two reasons:
47 // 1) TryLock() under Windows is a bit annoying (it requires a
48 //    #define to be defined very early).
49 // 2) TryLock() is broken for NO_THREADS mode, at least in NDEBUG
50 //    mode.
51 // If you need TryLock(), and either these two caveats are not a
52 // problem for you, or you're willing to work around them, then
53 // feel free to #define GMUTEX_TRYLOCK, or to remove the #ifdefs
54 // in the code below.
55 //
56 // CYGWIN NOTE: Cygwin support for rwlock seems to be buggy:
57 //    http://www.cygwin.com/ml/cygwin/2008-12/msg00017.html
58 // Because of that, we might as well use windows locks for
59 // cygwin.  They seem to be more reliable than the cygwin pthreads layer.
60 //
61 // TRICKY IMPLEMENTATION NOTE:
62 // This class is designed to be safe to use during
63 // dynamic-initialization -- that is, by global constructors that are
64 // run before main() starts.  The issue in this case is that
65 // dynamic-initialization happens in an unpredictable order, and it
66 // could be that someone else's dynamic initializer could call a
67 // function that tries to acquire this mutex -- but that all happens
68 // before this mutex's constructor has run.  (This can happen even if
69 // the mutex and the function that uses the mutex are in the same .cc
70 // file.)  Basically, because Mutex does non-trivial work in its
71 // constructor, it's not, in the naive implementation, safe to use
72 // before dynamic initialization has run on it.
73 //
74 // The solution used here is to pair the actual mutex primitive with a
75 // bool that is set to true when the mutex is dynamically initialized.
76 // (Before that it's false.)  Then we modify all mutex routines to
77 // look at the bool, and not try to lock/unlock until the bool makes
78 // it to true (which happens after the Mutex constructor has run.)
79 //
80 // This works because before main() starts -- particularly, during
81 // dynamic initialization -- there are no threads, so a) it's ok that
82 // the mutex operations are a no-op, since we don't need locking then
83 // anyway; and b) we can be quite confident our bool won't change
84 // state between a call to Lock() and a call to Unlock() (that would
85 // require a global constructor in one translation unit to call Lock()
86 // and another global constructor in another translation unit to call
87 // Unlock() later, which is pretty perverse).
88 //
89 // That said, it's tricky, and can conceivably fail; it's safest to
90 // avoid trying to acquire a mutex in a global constructor, if you
91 // can.  One way it can fail is that a really smart compiler might
92 // initialize the bool to true at static-initialization time (too
93 // early) rather than at dynamic-initialization time.  To discourage
94 // that, we set is_safe_ to true in code (not the constructor
95 // colon-initializer) and set it to true via a function that always
96 // evaluates to true, but that the compiler can't know always
97 // evaluates to true.  This should be good enough.
98 
99 #ifndef GOOGLE_MUTEX_H_
100 #define GOOGLE_MUTEX_H_
101 
102 #include "config.h"           // to figure out pthreads support
103 
104 #if defined(NO_THREADS)
105   typedef int MutexType;      // to keep a lock-count
106 #elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
107 # define WIN32_LEAN_AND_MEAN  // We only need minimal includes
108 # ifdef GMUTEX_TRYLOCK
109   // We need Windows NT or later for TryEnterCriticalSection().  If you
110   // don't need that functionality, you can remove these _WIN32_WINNT
111   // lines, and change TryLock() to assert(0) or something.
112 #   ifndef _WIN32_WINNT
113 #     define _WIN32_WINNT 0x0400
114 #   endif
115 # endif
116 # include <windows.h>
117   typedef CRITICAL_SECTION MutexType;
118 #elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK)
119   // Needed for pthread_rwlock_*.  If it causes problems, you could take it
120   // out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it
121   // *does* cause problems for FreeBSD, or MacOSX, but isn't needed
122   // for locking there.)
123 # ifdef __linux__
124 #   define _XOPEN_SOURCE 500  // may be needed to get the rwlock calls
125 # endif
126 # include <pthread.h>
127   typedef pthread_rwlock_t MutexType;
128 #elif defined(HAVE_PTHREAD)
129 # include <pthread.h>
130   typedef pthread_mutex_t MutexType;
131 #else
132 # error Need to implement mutex.h for your architecture, or #define NO_THREADS
133 #endif
134 
135 class Mutex {
136  public:
137   // Create a Mutex that is not held by anybody.  This constructor is
138   // typically used for Mutexes allocated on the heap or the stack.
139   // See below for a recommendation for constructing global Mutex
140   // objects.
141   inline Mutex();
142 
143   // Destructor
144   inline ~Mutex();
145 
146   inline void Lock();    // Block if needed until free then acquire exclusively
147   inline void Unlock();  // Release a lock acquired via Lock()
148 #ifdef GMUTEX_TRYLOCK
149   inline bool TryLock(); // If free, Lock() and return true, else return false
150 #endif
151   // Note that on systems that don't support read-write locks, these may
152   // be implemented as synonyms to Lock() and Unlock().  So you can use
153   // these for efficiency, but don't use them anyplace where being able
154   // to do shared reads is necessary to avoid deadlock.
155   inline void ReaderLock();   // Block until free or shared then acquire a share
156   inline void ReaderUnlock(); // Release a read share of this Mutex
WriterLock()157   inline void WriterLock() { Lock(); }     // Acquire an exclusive lock
WriterUnlock()158   inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock()
159 
160  private:
161   MutexType mutex_;
162   // We want to make sure that the compiler sets is_safe_ to true only
163   // when we tell it to, and never makes assumptions is_safe_ is
164   // always true.  volatile is the most reliable way to do that.
165   volatile bool is_safe_;
166 
SetIsSafe()167   inline void SetIsSafe() { is_safe_ = true; }
168 
169   // Catch the error of writing Mutex when intending MutexLock.
Mutex(Mutex *)170   Mutex(Mutex* /*ignored*/) {}
171   // Disallow "evil" constructors
172   Mutex(const Mutex&);
173   void operator=(const Mutex&);
174 };
175 
176 // Now the implementation of Mutex for various systems
177 #if defined(NO_THREADS)
178 
179 // When we don't have threads, we can be either reading or writing,
180 // but not both.  We can have lots of readers at once (in no-threads
181 // mode, that's most likely to happen in recursive function calls),
182 // but only one writer.  We represent this by having mutex_ be -1 when
183 // writing and a number > 0 when reading (and 0 when no lock is held).
184 //
185 // In debug mode, we assert these invariants, while in non-debug mode
186 // we do nothing, for efficiency.  That's why everything is in an
187 // assert.
188 #include <assert.h>
189 
Mutex()190 Mutex::Mutex() : mutex_(0) { }
~Mutex()191 Mutex::~Mutex()            { assert(mutex_ == 0); }
Lock()192 void Mutex::Lock()         { assert(--mutex_ == -1); }
Unlock()193 void Mutex::Unlock()       { assert(mutex_++ == -1); }
194 #ifdef GMUTEX_TRYLOCK
TryLock()195 bool Mutex::TryLock()      { if (mutex_) return false; Lock(); return true; }
196 #endif
ReaderLock()197 void Mutex::ReaderLock()   { assert(++mutex_ > 0); }
ReaderUnlock()198 void Mutex::ReaderUnlock() { assert(mutex_-- > 0); }
199 
200 #elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
201 
Mutex()202 Mutex::Mutex()             { InitializeCriticalSection(&mutex_); SetIsSafe(); }
~Mutex()203 Mutex::~Mutex()            { DeleteCriticalSection(&mutex_); }
Lock()204 void Mutex::Lock()         { if (is_safe_) EnterCriticalSection(&mutex_); }
Unlock()205 void Mutex::Unlock()       { if (is_safe_) LeaveCriticalSection(&mutex_); }
206 #ifdef GMUTEX_TRYLOCK
TryLock()207 bool Mutex::TryLock()      { return is_safe_ ?
208                                  TryEnterCriticalSection(&mutex_) != 0 : true; }
209 #endif
ReaderLock()210 void Mutex::ReaderLock()   { Lock(); }      // we don't have read-write locks
ReaderUnlock()211 void Mutex::ReaderUnlock() { Unlock(); }
212 
213 #elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK)
214 
215 #include <stdlib.h>      // for abort()
216 #define SAFE_PTHREAD(fncall)  do {   /* run fncall if is_safe_ is true */  \
217   if (is_safe_ && fncall(&mutex_) != 0) abort();                           \
218 } while (0)
219 
Mutex()220 Mutex::Mutex() {
221   SetIsSafe();
222   if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
223 }
~Mutex()224 Mutex::~Mutex()            { SAFE_PTHREAD(pthread_rwlock_destroy); }
Lock()225 void Mutex::Lock()         { SAFE_PTHREAD(pthread_rwlock_wrlock); }
Unlock()226 void Mutex::Unlock()       { SAFE_PTHREAD(pthread_rwlock_unlock); }
227 #ifdef GMUTEX_TRYLOCK
TryLock()228 bool Mutex::TryLock()      { return is_safe_ ?
229                                     pthread_rwlock_trywrlock(&mutex_) == 0 :
230                                     true; }
231 #endif
ReaderLock()232 void Mutex::ReaderLock()   { SAFE_PTHREAD(pthread_rwlock_rdlock); }
ReaderUnlock()233 void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); }
234 #undef SAFE_PTHREAD
235 
236 #elif defined(HAVE_PTHREAD)
237 
238 #include <stdlib.h>      // for abort()
239 #define SAFE_PTHREAD(fncall)  do {   /* run fncall if is_safe_ is true */  \
240   if (is_safe_ && fncall(&mutex_) != 0) abort();                           \
241 } while (0)
242 
Mutex()243 Mutex::Mutex()             {
244   SetIsSafe();
245   if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
246 }
~Mutex()247 Mutex::~Mutex()            { SAFE_PTHREAD(pthread_mutex_destroy); }
Lock()248 void Mutex::Lock()         { SAFE_PTHREAD(pthread_mutex_lock); }
Unlock()249 void Mutex::Unlock()       { SAFE_PTHREAD(pthread_mutex_unlock); }
250 #ifdef GMUTEX_TRYLOCK
TryLock()251 bool Mutex::TryLock()      { return is_safe_ ?
252                                  pthread_mutex_trylock(&mutex_) == 0 : true; }
253 #endif
ReaderLock()254 void Mutex::ReaderLock()   { Lock(); }
ReaderUnlock()255 void Mutex::ReaderUnlock() { Unlock(); }
256 #undef SAFE_PTHREAD
257 
258 #endif
259 
260 // --------------------------------------------------------------------------
261 // Some helper classes
262 
263 // MutexLock(mu) acquires mu when constructed and releases it when destroyed.
264 class MutexLock {
265  public:
MutexLock(Mutex * mu)266   explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); }
~MutexLock()267   ~MutexLock() { mu_->Unlock(); }
268  private:
269   Mutex * const mu_;
270   // Disallow "evil" constructors
271   MutexLock(const MutexLock&);
272   void operator=(const MutexLock&);
273 };
274 
275 // ReaderMutexLock and WriterMutexLock do the same, for rwlocks
276 class ReaderMutexLock {
277  public:
ReaderMutexLock(Mutex * mu)278   explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); }
~ReaderMutexLock()279   ~ReaderMutexLock() { mu_->ReaderUnlock(); }
280  private:
281   Mutex * const mu_;
282   // Disallow "evil" constructors
283   ReaderMutexLock(const ReaderMutexLock&);
284   void operator=(const ReaderMutexLock&);
285 };
286 
287 class WriterMutexLock {
288  public:
WriterMutexLock(Mutex * mu)289   explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); }
~WriterMutexLock()290   ~WriterMutexLock() { mu_->WriterUnlock(); }
291  private:
292   Mutex * const mu_;
293   // Disallow "evil" constructors
294   WriterMutexLock(const WriterMutexLock&);
295   void operator=(const WriterMutexLock&);
296 };
297 
298 // Catch bug where variable name is omitted, e.g. MutexLock (&mu);
299 #define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_decl_missing_var_name)
300 #define ReaderMutexLock(x) COMPILE_ASSERT(0, rmutex_lock_decl_missing_var_name)
301 #define WriterMutexLock(x) COMPILE_ASSERT(0, wmutex_lock_decl_missing_var_name)
302 
303 #endif  /* #define GOOGLE_MUTEX_H__ */
304