blob: 3962a6de5751e0fea3f62beccc979b2f2a1b630b [file] [log] [blame]
Brian Silverman70325d62015-09-20 17:00:43 -04001// 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>
115#if defined(NO_THREADS)
116 typedef int MutexType; // to keep a lock-count
117#elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
118# ifndef WIN32_LEAN_AND_MEAN
119# define WIN32_LEAN_AND_MEAN // We only need minimal includes
120# endif
121# ifndef NOMINMAX
122# define NOMINMAX // Don't want windows to override min()/max()
123# endif
124# ifdef GMUTEX_TRYLOCK
125 // We need Windows NT or later for TryEnterCriticalSection(). If you
126 // don't need that functionality, you can remove these _WIN32_WINNT
127 // lines, and change TryLock() to assert(0) or something.
128# ifndef _WIN32_WINNT
129# define _WIN32_WINNT 0x0400
130# endif
131# endif
132# include <windows.h>
133 typedef CRITICAL_SECTION MutexType;
134#elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK)
135 // Needed for pthread_rwlock_*. If it causes problems, you could take it
136 // out, but then you'd have to unset HAVE_RWLOCK (at least on linux -- it
137 // *does* cause problems for FreeBSD, or MacOSX, but isn't needed
138 // for locking there.)
139# ifdef __linux__
140# if _XOPEN_SOURCE < 500 // including not being defined at all
141# undef _XOPEN_SOURCE
142# define _XOPEN_SOURCE 500 // may be needed to get the rwlock calls
143# endif
144# endif
145#if defined(HAVE_PTHREAD) && !defined(NO_THREADS)
146# include <pthread.h>
147#endif
148 typedef pthread_rwlock_t MutexType;
149#elif defined(HAVE_PTHREAD)
150#if defined(HAVE_PTHREAD) && !defined(NO_THREADS)
151# include <pthread.h>
152#endif
153 typedef pthread_mutex_t MutexType;
154#else
155# error Need to implement mutex.h for your architecture, or #define NO_THREADS
156#endif
157
158#include <assert.h>
159#include <stdlib.h> // for abort()
160
161namespace ctemplate {
162
163namespace base {
164// This is used for the single-arg constructor
165enum LinkerInitialized { LINKER_INITIALIZED };
166}
167
168class Mutex {
169 public:
170 // Create a Mutex that is not held by anybody. This constructor is
171 // typically used for Mutexes allocated on the heap or the stack.
172 inline Mutex();
173 // This constructor should be used for global, static Mutex objects.
174 // It inhibits work being done by the destructor, which makes it
175 // safer for code that tries to acqiure this mutex in their global
176 // destructor.
177 inline Mutex(base::LinkerInitialized);
178
179 // Destructor
180 inline ~Mutex();
181
182 inline void Lock(); // Block if needed until free then acquire exclusively
183 inline void Unlock(); // Release a lock acquired via Lock()
184#ifdef GMUTEX_TRYLOCK
185 inline bool TryLock(); // If free, Lock() and return true, else return false
186#endif
187 // Note that on systems that don't support read-write locks, these may
188 // be implemented as synonyms to Lock() and Unlock(). So you can use
189 // these for efficiency, but don't use them anyplace where being able
190 // to do shared reads is necessary to avoid deadlock.
191 inline void ReaderLock(); // Block until free or shared then acquire a share
192 inline void ReaderUnlock(); // Release a read share of this Mutex
193 inline void WriterLock() { Lock(); } // Acquire an exclusive lock
194 inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock()
195
196 private:
197 MutexType mutex_;
198 // We want to make sure that the compiler sets is_safe_ to true only
199 // when we tell it to, and never makes assumptions is_safe_ is
200 // always true. volatile is the most reliable way to do that.
201 volatile bool is_safe_;
202 // This indicates which constructor was called.
203 bool destroy_;
204
205 inline void SetIsSafe() { is_safe_ = true; }
206
207 // Catch the error of writing Mutex when intending MutexLock.
208 Mutex(Mutex* /*ignored*/) {}
209 // Disallow "evil" constructors
210 Mutex(const Mutex&);
211 void operator=(const Mutex&);
212};
213
214// We will also define GoogleOnceType, GOOGLE_ONCE_INIT, and
215// GoogleOnceInit, which are portable versions of pthread_once_t,
216// PTHREAD_ONCE_INIT, and pthread_once.
217
218// Now the implementation of Mutex for various systems
219#if defined(NO_THREADS)
220
221// When we don't have threads, we can be either reading or writing,
222// but not both. We can have lots of readers at once (in no-threads
223// mode, that's most likely to happen in recursive function calls),
224// but only one writer. We represent this by having mutex_ be -1 when
225// writing and a number > 0 when reading (and 0 when no lock is held).
226//
227// In debug mode, we assert these invariants, while in non-debug mode
228// we do nothing, for efficiency. That's why everything is in an
229// assert.
230
231Mutex::Mutex() : mutex_(0) { }
232Mutex::Mutex(base::LinkerInitialized) : mutex_(0) { }
233Mutex::~Mutex() { assert(mutex_ == 0); }
234void Mutex::Lock() { assert(--mutex_ == -1); }
235void Mutex::Unlock() { assert(mutex_++ == -1); }
236#ifdef GMUTEX_TRYLOCK
237bool Mutex::TryLock() { if (mutex_) return false; Lock(); return true; }
238#endif
239void Mutex::ReaderLock() { assert(++mutex_ > 0); }
240void Mutex::ReaderUnlock() { assert(mutex_-- > 0); }
241
242typedef int GoogleOnceType;
243const GoogleOnceType GOOGLE_ONCE_INIT = 0;
244inline int GoogleOnceInit(GoogleOnceType* once_control,
245 void (*init_routine)(void)) {
246 if ((*once_control)++ == 0)
247 (*init_routine)();
248 return 0;
249}
250
251#elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
252
253Mutex::Mutex() : destroy_(true) {
254 InitializeCriticalSection(&mutex_);
255 SetIsSafe();
256}
257Mutex::Mutex(base::LinkerInitialized) : destroy_(false) {
258 InitializeCriticalSection(&mutex_);
259 SetIsSafe();
260}
261Mutex::~Mutex() { if (destroy_) DeleteCriticalSection(&mutex_); }
262void Mutex::Lock() { if (is_safe_) EnterCriticalSection(&mutex_); }
263void Mutex::Unlock() { if (is_safe_) LeaveCriticalSection(&mutex_); }
264#ifdef GMUTEX_TRYLOCK
265bool Mutex::TryLock() { return is_safe_ ?
266 TryEnterCriticalSection(&mutex_) != 0 : true; }
267#endif
268void Mutex::ReaderLock() { Lock(); } // we don't have read-write locks
269void Mutex::ReaderUnlock() { Unlock(); }
270
271// We do a simple spinlock for pthread_once_t. See
272// http://www.ddj.com/cpp/199203083?pgno=3
273#ifdef INTERLOCKED_EXCHANGE_NONVOLATILE
274typedef LONG GoogleOnceType;
275#else
276typedef volatile LONG GoogleOnceType;
277#endif
278const GoogleOnceType GOOGLE_ONCE_INIT = 0;
279inline int GoogleOnceInit(GoogleOnceType* once_control,
280 void (*init_routine)(void)) {
281 while (1) {
282 LONG prev = InterlockedCompareExchange(once_control, 1, 0);
283 if (prev == 2) { // We've successfully initted in the past.
284 return 0;
285 } else if (prev == 0) { // No init yet, but we have the lock.
286 (*init_routine)();
287 InterlockedExchange(once_control, 2);
288 return 0;
289 } else { // Someone else is holding the lock, so wait.
290 assert(1 == prev);
291 Sleep(1); // sleep for 1ms
292 }
293 }
294 return 1; // unreachable
295}
296
297#elif defined(HAVE_PTHREAD) && defined(HAVE_RWLOCK)
298
299#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \
300 if (is_safe_ && fncall(&mutex_) != 0) abort(); \
301} while (0)
302
303Mutex::Mutex() : destroy_(true) {
304 SetIsSafe();
305 if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
306}
307Mutex::Mutex(base::LinkerInitialized) : destroy_(false) {
308 SetIsSafe();
309 if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
310}
311Mutex::~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_rwlock_destroy); }
312void Mutex::Lock() { SAFE_PTHREAD(pthread_rwlock_wrlock); }
313void Mutex::Unlock() { SAFE_PTHREAD(pthread_rwlock_unlock); }
314#ifdef GMUTEX_TRYLOCK
315bool Mutex::TryLock() { return is_safe_ ?
316 pthread_rwlock_trywrlock(&mutex_) == 0 : true; }
317#endif
318void Mutex::ReaderLock() { SAFE_PTHREAD(pthread_rwlock_rdlock); }
319void Mutex::ReaderUnlock() { SAFE_PTHREAD(pthread_rwlock_unlock); }
320#undef SAFE_PTHREAD
321
322typedef pthread_once_t GoogleOnceType;
323const GoogleOnceType GOOGLE_ONCE_INIT = PTHREAD_ONCE_INIT;
324inline int GoogleOnceInit(GoogleOnceType* once_control,
325 void (*init_routine)(void)) {
326 return pthread_once(once_control, init_routine);
327}
328
329#elif defined(HAVE_PTHREAD)
330
331#define SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \
332 if (is_safe_ && fncall(&mutex_) != 0) abort(); \
333} while (0)
334
335Mutex::Mutex() : destroy_(true) {
336 SetIsSafe();
337 if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
338}
339Mutex::Mutex(base::LinkerInitialized) : destroy_(false) {
340 SetIsSafe();
341 if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
342}
343Mutex::~Mutex() { if (destroy_) SAFE_PTHREAD(pthread_mutex_destroy); }
344void Mutex::Lock() { SAFE_PTHREAD(pthread_mutex_lock); }
345void Mutex::Unlock() { SAFE_PTHREAD(pthread_mutex_unlock); }
346#ifdef GMUTEX_TRYLOCK
347bool Mutex::TryLock() { return is_safe_ ?
348 pthread_mutex_trylock(&mutex_) == 0 : true; }
349#endif
350void Mutex::ReaderLock() { Lock(); }
351void Mutex::ReaderUnlock() { Unlock(); }
352#undef SAFE_PTHREAD
353
354typedef pthread_once_t GoogleOnceType;
355const GoogleOnceType GOOGLE_ONCE_INIT = PTHREAD_ONCE_INIT;
356inline int GoogleOnceInit(GoogleOnceType* once_control,
357 void (*init_routine)(void)) {
358 return pthread_once(once_control, init_routine);
359}
360
361#endif
362
363// --------------------------------------------------------------------------
364// Some helper classes
365
366// MutexLock(mu) acquires mu when constructed and releases it when destroyed.
367class MutexLock {
368 public:
369 explicit MutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); }
370 ~MutexLock() { mu_->Unlock(); }
371 private:
372 Mutex * const mu_;
373 // Disallow "evil" constructors
374 MutexLock(const MutexLock&);
375 void operator=(const MutexLock&);
376};
377
378// ReaderMutexLock and WriterMutexLock do the same, for rwlocks
379class ReaderMutexLock {
380 public:
381 explicit ReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); }
382 ~ReaderMutexLock() { mu_->ReaderUnlock(); }
383 private:
384 Mutex * const mu_;
385 // Disallow "evil" constructors
386 ReaderMutexLock(const ReaderMutexLock&);
387 void operator=(const ReaderMutexLock&);
388};
389
390class WriterMutexLock {
391 public:
392 explicit WriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); }
393 ~WriterMutexLock() { mu_->WriterUnlock(); }
394 private:
395 Mutex * const mu_;
396 // Disallow "evil" constructors
397 WriterMutexLock(const WriterMutexLock&);
398 void operator=(const WriterMutexLock&);
399};
400
401// Catch bug where variable name is omitted, e.g. MutexLock (&mu);
402#define MutexLock(x) COMPILE_ASSERT(0, mutex_lock_decl_missing_var_name)
403#define ReaderMutexLock(x) COMPILE_ASSERT(0, rmutex_lock_decl_missing_var_name)
404#define WriterMutexLock(x) COMPILE_ASSERT(0, wmutex_lock_decl_missing_var_name)
405
406}
407
408#endif /* #define GOOGLE_MUTEX_H__ */