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