PageRenderTime 25ms CodeModel.GetById 7ms app.highlight 14ms RepoModel.GetById 1ms app.codeStats 0ms

/thirdparty/breakpad/third_party/glog/src/base/mutex.h

http://github.com/tomahawk-player/tomahawk
C++ Header | 325 lines | 147 code | 34 blank | 144 comment | 30 complexity | ce5bb9b20411aecc506601ba66029995 MD5 | raw file
  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 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.
 47//
 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
 53//    mode.
 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
 57// in the code below.
 58//
 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.
 63//
 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.
 76//
 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.)
 82//
 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).
 91//
 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.
101
102#ifndef GOOGLE_MUTEX_H_
103#define GOOGLE_MUTEX_H_
104
105#include "config.h"           // to figure out pthreads support
106
107#if defined(NO_THREADS)
108  typedef int MutexType;      // to keep a lock-count
109#elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
110# define WIN32_LEAN_AND_MEAN  // We only need minimal includes
111# ifdef GMUTEX_TRYLOCK
112  // We need Windows NT or later for TryEnterCriticalSection().  If you
113  // don't need that functionality, you can remove these _WIN32_WINNT
114  // lines, and change TryLock() to assert(0) or something.
115#   ifndef _WIN32_WINNT
116#     define _WIN32_WINNT 0x0400
117#   endif
118# endif
119// To avoid macro definition of ERROR.
120# define NOGDI
121// To avoid macro definition of min/max.
122# define NOMINMAX
123# include <windows.h>
124  typedef CRITICAL_SECTION MutexType;
125#elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK)
126  // Needed for pthread_rwlock_*.  If it causes problems, you could take it
127  // out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it
128  // *does* cause problems for FreeBSD, or MacOSX, but isn't needed
129  // for locking there.)
130# ifdef __linux__
131#   define _XOPEN_SOURCE 500  // may be needed to get the rwlock calls
132# endif
133# include <pthread.h>
134  typedef pthread_rwlock_t MutexType;
135#elif defined(HAVE_PTHREAD)
136# include <pthread.h>
137  typedef pthread_mutex_t MutexType;
138#else
139# error Need to implement mutex.h for your architecture, or #define NO_THREADS
140#endif
141
142// We need to include these header files after defining _XOPEN_SOURCE
143// as they may define the _XOPEN_SOURCE macro.
144#include <assert.h>
145#include <stdlib.h>      // for abort()
146
147#define MUTEX_NAMESPACE glog_internal_namespace_
148
149namespace MUTEX_NAMESPACE {
150
151class Mutex {
152 public:
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  // See below for a recommendation for constructing global Mutex
156  // objects.
157  inline Mutex();
158
159  // Destructor
160  inline ~Mutex();
161
162  inline void Lock();    // Block if needed until free then acquire exclusively
163  inline void Unlock();  // Release a lock acquired via Lock()
164#ifdef GMUTEX_TRYLOCK
165  inline bool TryLock(); // If free, Lock() and return true, else return false
166#endif
167  // Note that on systems that don't support read-write locks, these may
168  // be implemented as synonyms to Lock() and Unlock().  So you can use
169  // these for efficiency, but don't use them anyplace where being able
170  // to do shared reads is necessary to avoid deadlock.
171  inline void ReaderLock();   // Block until free or shared then acquire a share
172  inline void ReaderUnlock(); // Release a read share of this Mutex
173  inline void WriterLock() { Lock(); }     // Acquire an exclusive lock
174  inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock()
175
176  // TODO(hamaji): Do nothing, implement correctly.
177  inline void AssertHeld() {}
178
179 private:
180  MutexType mutex_;
181  // We want to make sure that the compiler sets is_safe_ to true only
182  // when we tell it to, and never makes assumptions is_safe_ is
183  // always true.  volatile is the most reliable way to do that.
184  volatile bool is_safe_;
185
186  inline void SetIsSafe() { is_safe_ = true; }
187
188  // Catch the error of writing Mutex when intending MutexLock.
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
208Mutex::Mutex() : mutex_(0) { }
209Mutex::~Mutex()            { assert(mutex_ == 0); }
210void Mutex::Lock()         { assert(--mutex_ == -1); }
211void Mutex::Unlock()       { assert(mutex_++ == -1); }
212#ifdef GMUTEX_TRYLOCK
213bool Mutex::TryLock()      { if (mutex_) return false; Lock(); return true; }
214#endif
215void Mutex::ReaderLock()   { assert(++mutex_ > 0); }
216void Mutex::ReaderUnlock() { assert(mutex_-- > 0); }
217
218#elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
219
220Mutex::Mutex()             { InitializeCriticalSection(&mutex_); SetIsSafe(); }
221Mutex::~Mutex()            { DeleteCriticalSection(&mutex_); }
222void Mutex::Lock()         { if (is_safe_) EnterCriticalSection(&mutex_); }
223void Mutex::Unlock()       { if (is_safe_) LeaveCriticalSection(&mutex_); }
224#ifdef GMUTEX_TRYLOCK
225bool Mutex::TryLock()      { return is_safe_ ?
226                                 TryEnterCriticalSection(&mutex_) != 0 : true; }
227#endif
228void Mutex::ReaderLock()   { Lock(); }      // we don't have read-write locks
229void Mutex::ReaderUnlock() { Unlock(); }
230
231#elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK)
232
233#define SAFE_PTHREAD(fncall)  do {   /* run fncall if is_safe_ is true */  \
234  if (is_safe_ && fncall(&mutex_) != 0) abort();                           \
235} while (0)
236
237Mutex::Mutex() {
238  SetIsSafe();
239  if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
240}
241Mutex::~Mutex()            { SAFE_PTHREAD(pthread_rwlock_destroy); }
242void Mutex::Lock()         { SAFE_PTHREAD(pthread_rwlock_wrlock); }
243void Mutex::Unlock()       { SAFE_PTHREAD(pthread_rwlock_unlock); }
244#ifdef GMUTEX_TRYLOCK
245bool Mutex::TryLock()      { return is_safe_ ?
246                                    pthread_rwlock_trywrlock(&mutex_) == 0 :
247                                    true; }
248#endif
249void Mutex::ReaderLock()   { SAFE_PTHREAD(pthread_rwlock_rdlock); }
250void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); }
251#undef SAFE_PTHREAD
252
253#elif defined(HAVE_PTHREAD)
254
255#define SAFE_PTHREAD(fncall)  do {   /* run fncall if is_safe_ is true */  \
256  if (is_safe_ && fncall(&mutex_) != 0) abort();                           \
257} while (0)
258
259Mutex::Mutex()             {
260  SetIsSafe();
261  if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
262}
263Mutex::~Mutex()            { SAFE_PTHREAD(pthread_mutex_destroy); }
264void Mutex::Lock()         { SAFE_PTHREAD(pthread_mutex_lock); }
265void Mutex::Unlock()       { SAFE_PTHREAD(pthread_mutex_unlock); }
266#ifdef GMUTEX_TRYLOCK
267bool Mutex::TryLock()      { return is_safe_ ?
268                                 pthread_mutex_trylock(&mutex_) == 0 : true; }
269#endif
270void Mutex::ReaderLock()   { Lock(); }
271void Mutex::ReaderUnlock() { Unlock(); }
272#undef SAFE_PTHREAD
273
274#endif
275
276// --------------------------------------------------------------------------
277// Some helper classes
278
279// MutexLock(mu) acquires mu when constructed and releases it when destroyed.
280class MutexLock {
281 public:
282  explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); }
283  ~MutexLock() { mu_->Unlock(); }
284 private:
285  Mutex * const mu_;
286  // Disallow "evil" constructors
287  MutexLock(const MutexLock&);
288  void operator=(const MutexLock&);
289};
290
291// ReaderMutexLock and WriterMutexLock do the same, for rwlocks
292class ReaderMutexLock {
293 public:
294  explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); }
295  ~ReaderMutexLock() { mu_->ReaderUnlock(); }
296 private:
297  Mutex * const mu_;
298  // Disallow "evil" constructors
299  ReaderMutexLock(const ReaderMutexLock&);
300  void operator=(const ReaderMutexLock&);
301};
302
303class WriterMutexLock {
304 public:
305  explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); }
306  ~WriterMutexLock() { mu_->WriterUnlock(); }
307 private:
308  Mutex * const mu_;
309  // Disallow "evil" constructors
310  WriterMutexLock(const WriterMutexLock&);
311  void operator=(const WriterMutexLock&);
312};
313
314// Catch bug where variable name is omitted, e.g. MutexLock (&mu);
315#define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_decl_missing_var_name)
316#define ReaderMutexLock(x) COMPILE_ASSERT(0, rmutex_lock_decl_missing_var_name)
317#define WriterMutexLock(x) COMPILE_ASSERT(0, wmutex_lock_decl_missing_var_name)
318
319}  // namespace MUTEX_NAMESPACE
320
321using namespace MUTEX_NAMESPACE;
322
323#undef MUTEX_NAMESPACE
324
325#endif  /* #define GOOGLE_MUTEX_H__ */