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