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