Imported Upstream version ceres 1.13.0
[platform/upstream/ceres-solver.git] / internal / ceres / mutex.h
1 // Ceres Solver - A fast non-linear least squares minimizer
2 // Copyright 2015 Google Inc. All rights reserved.
3 // http://ceres-solver.org/
4 //
5 // Redistribution and use in source and binary forms, with or without
6 // modification, are permitted provided that the following conditions are met:
7 //
8 // * Redistributions of source code must retain the above copyright notice,
9 //   this list of conditions and the following disclaimer.
10 // * Redistributions in binary form must reproduce the above copyright notice,
11 //   this list of conditions and the following disclaimer in the documentation
12 //   and/or other materials provided with the distribution.
13 // * Neither the name of Google Inc. nor the names of its contributors may be
14 //   used to endorse or promote products derived from this software without
15 //   specific prior written permission.
16 //
17 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
18 // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
21 // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
22 // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
23 // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
24 // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
25 // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
26 // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
27 // POSSIBILITY OF SUCH DAMAGE.
28 //
29 // Author: Craig Silverstein.
30 //
31 // A simple mutex wrapper, supporting locks and read-write locks.
32 // You should assume the locks are *not* re-entrant.
33 //
34 // This class is meant to be internal-only and should be wrapped by an
35 // internal namespace.  Before you use this module, please give the
36 // name of your internal namespace for this module.  Or, if you want
37 // to expose it, you'll want to move it to the Google namespace.  We
38 // cannot put this class in global namespace because there can be some
39 // problems when we have multiple versions of Mutex in each shared object.
40 //
41 // NOTE: by default, we have #ifdef'ed out the TryLock() method.
42 //       This is for two reasons:
43 // 1) TryLock() under Windows is a bit annoying (it requires a
44 //    #define to be defined very early).
45 // 2) TryLock() is broken for NO_THREADS mode, at least in NDEBUG
46 //    mode.
47 // If you need TryLock(), and either these two caveats are not a
48 // problem for you, or you're willing to work around them, then
49 // feel free to #define GMUTEX_TRYLOCK, or to remove the #ifdefs
50 // in the code below.
51 //
52 // CYGWIN NOTE: Cygwin support for rwlock seems to be buggy:
53 //    http://www.cygwin.com/ml/cygwin/2008-12/msg00017.html
54 // Because of that, we might as well use windows locks for
55 // cygwin.  They seem to be more reliable than the cygwin pthreads layer.
56 //
57 // TRICKY IMPLEMENTATION NOTE:
58 // This class is designed to be safe to use during
59 // dynamic-initialization -- that is, by global constructors that are
60 // run before main() starts.  The issue in this case is that
61 // dynamic-initialization happens in an unpredictable order, and it
62 // could be that someone else's dynamic initializer could call a
63 // function that tries to acquire this mutex -- but that all happens
64 // before this mutex's constructor has run.  (This can happen even if
65 // the mutex and the function that uses the mutex are in the same .cc
66 // file.)  Basically, because Mutex does non-trivial work in its
67 // constructor, it's not, in the naive implementation, safe to use
68 // before dynamic initialization has run on it.
69 //
70 // The solution used here is to pair the actual mutex primitive with a
71 // bool that is set to true when the mutex is dynamically initialized.
72 // (Before that it's false.)  Then we modify all mutex routines to
73 // look at the bool, and not try to lock/unlock until the bool makes
74 // it to true (which happens after the Mutex constructor has run.)
75 //
76 // This works because before main() starts -- particularly, during
77 // dynamic initialization -- there are no threads, so a) it's ok that
78 // the mutex operations are a no-op, since we don't need locking then
79 // anyway; and b) we can be quite confident our bool won't change
80 // state between a call to Lock() and a call to Unlock() (that would
81 // require a global constructor in one translation unit to call Lock()
82 // and another global constructor in another translation unit to call
83 // Unlock() later, which is pretty perverse).
84 //
85 // That said, it's tricky, and can conceivably fail; it's safest to
86 // avoid trying to acquire a mutex in a global constructor, if you
87 // can.  One way it can fail is that a really smart compiler might
88 // initialize the bool to true at static-initialization time (too
89 // early) rather than at dynamic-initialization time.  To discourage
90 // that, we set is_safe_ to true in code (not the constructor
91 // colon-initializer) and set it to true via a function that always
92 // evaluates to true, but that the compiler can't know always
93 // evaluates to true.  This should be good enough.
94
95 #ifndef CERES_INTERNAL_MUTEX_H_
96 #define CERES_INTERNAL_MUTEX_H_
97
98 #include "ceres/internal/port.h"
99
100 #if defined(CERES_NO_THREADS)
101   typedef int MutexType;      // to keep a lock-count
102 #elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
103 # define CERES_WIN32_LEAN_AND_MEAN  // We only need minimal includes
104 # ifdef CERES_GMUTEX_TRYLOCK
105   // We need Windows NT or later for TryEnterCriticalSection().  If you
106   // don't need that functionality, you can remove these _WIN32_WINNT
107   // lines, and change TryLock() to assert(0) or something.
108 #   ifndef _WIN32_WINNT
109 #     define _WIN32_WINNT 0x0400
110 #   endif
111 # endif
112 // Unfortunately, windows.h defines a bunch of macros with common
113 // names. Two in particular need avoiding: ERROR and min/max.
114 // To avoid macro definition of ERROR.
115 # define NOGDI
116 // To avoid macro definition of min/max.
117 # ifndef NOMINMAX
118 #   define NOMINMAX
119 # endif
120 # include <windows.h>
121   typedef CRITICAL_SECTION MutexType;
122 #elif defined(CERES_HAVE_PTHREAD) && defined(CERES_HAVE_RWLOCK)
123   // Needed for pthread_rwlock_*.  If it causes problems, you could take it
124   // out, but then you'd have to unset CERES_HAVE_RWLOCK (at least on linux --
125   // it *does* cause problems for FreeBSD, or MacOSX, but isn't needed for
126   // locking there.)
127 # if defined(__linux__) && !defined(_XOPEN_SOURCE)
128 #   define _XOPEN_SOURCE 500  // may be needed to get the rwlock calls
129 # endif
130 # include <pthread.h>
131   typedef pthread_rwlock_t MutexType;
132 #elif defined(CERES_HAVE_PTHREAD)
133 # include <pthread.h>
134   typedef pthread_mutex_t MutexType;
135 #else
136 # error Need to implement mutex.h for your architecture, or #define NO_THREADS
137 #endif
138
139 // We need to include these header files after defining _XOPEN_SOURCE
140 // as they may define the _XOPEN_SOURCE macro.
141 #include <assert.h>
142 #include <stdlib.h>      // for abort()
143
144 namespace ceres {
145 namespace internal {
146
147 class Mutex {
148  public:
149   // Create a Mutex that is not held by anybody.  This constructor is
150   // typically used for Mutexes allocated on the heap or the stack.
151   // See below for a recommendation for constructing global Mutex
152   // objects.
153   inline Mutex();
154
155   // Destructor
156   inline ~Mutex();
157
158   inline void Lock();    // Block if needed until free then acquire exclusively
159   inline void Unlock();  // Release a lock acquired via Lock()
160 #ifdef CERES_GMUTEX_TRYLOCK
161   inline bool TryLock(); // If free, Lock() and return true, else return false
162 #endif
163   // Note that on systems that don't support read-write locks, these may
164   // be implemented as synonyms to Lock() and Unlock().  So you can use
165   // these for efficiency, but don't use them anyplace where being able
166   // to do shared reads is necessary to avoid deadlock.
167   inline void ReaderLock();   // Block until free or shared then acquire a share
168   inline void ReaderUnlock(); // Release a read share of this Mutex
169   inline void WriterLock() { Lock(); }     // Acquire an exclusive lock
170   inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock()
171
172   // TODO(hamaji): Do nothing, implement correctly.
173   inline void AssertHeld() {}
174
175  private:
176   MutexType mutex_;
177   // We want to make sure that the compiler sets is_safe_ to true only
178   // when we tell it to, and never makes assumptions is_safe_ is
179   // always true.  volatile is the most reliable way to do that.
180   volatile bool is_safe_;
181
182   inline void SetIsSafe() { is_safe_ = true; }
183
184   // Catch the error of writing Mutex when intending MutexLock.
185   Mutex(Mutex* /*ignored*/) {}
186   // Disallow "evil" constructors
187   Mutex(const Mutex&);
188   void operator=(const Mutex&);
189 };
190
191 // Now the implementation of Mutex for various systems
192 #if defined(CERES_NO_THREADS)
193
194 // When we don't have threads, we can be either reading or writing,
195 // but not both.  We can have lots of readers at once (in no-threads
196 // mode, that's most likely to happen in recursive function calls),
197 // but only one writer.  We represent this by having mutex_ be -1 when
198 // writing and a number > 0 when reading (and 0 when no lock is held).
199 //
200 // In debug mode, we assert these invariants, while in non-debug mode
201 // we do nothing, for efficiency.  That's why everything is in an
202 // assert.
203
204 Mutex::Mutex() : mutex_(0) { }
205 Mutex::~Mutex()            { assert(mutex_ == 0); }
206 void Mutex::Lock()         { assert(--mutex_ == -1); }
207 void Mutex::Unlock()       { assert(mutex_++ == -1); }
208 #ifdef CERES_GMUTEX_TRYLOCK
209 bool Mutex::TryLock()      { if (mutex_) return false; Lock(); return true; }
210 #endif
211 void Mutex::ReaderLock()   { assert(++mutex_ > 0); }
212 void Mutex::ReaderUnlock() { assert(mutex_-- > 0); }
213
214 #elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
215
216 Mutex::Mutex()             { InitializeCriticalSection(&mutex_); SetIsSafe(); }
217 Mutex::~Mutex()            { DeleteCriticalSection(&mutex_); }
218 void Mutex::Lock()         { if (is_safe_) EnterCriticalSection(&mutex_); }
219 void Mutex::Unlock()       { if (is_safe_) LeaveCriticalSection(&mutex_); }
220 #ifdef GMUTEX_TRYLOCK
221 bool Mutex::TryLock()      { return is_safe_ ?
222                                  TryEnterCriticalSection(&mutex_) != 0 : true; }
223 #endif
224 void Mutex::ReaderLock()   { Lock(); }      // we don't have read-write locks
225 void Mutex::ReaderUnlock() { Unlock(); }
226
227 #elif defined(CERES_HAVE_PTHREAD) && defined(CERES_HAVE_RWLOCK)
228
229 #define CERES_SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \
230   if (is_safe_ && fncall(&mutex_) != 0) abort();                             \
231 } while (0)
232
233 Mutex::Mutex() {
234   SetIsSafe();
235   if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
236 }
237 Mutex::~Mutex()            { CERES_SAFE_PTHREAD(pthread_rwlock_destroy); }
238 void Mutex::Lock()         { CERES_SAFE_PTHREAD(pthread_rwlock_wrlock); }
239 void Mutex::Unlock()       { CERES_SAFE_PTHREAD(pthread_rwlock_unlock); }
240 #ifdef CERES_GMUTEX_TRYLOCK
241 bool Mutex::TryLock()      { return is_safe_ ?
242                                     pthread_rwlock_trywrlock(&mutex_) == 0 :
243                                     true; }
244 #endif
245 void Mutex::ReaderLock()   { CERES_SAFE_PTHREAD(pthread_rwlock_rdlock); }
246 void Mutex::ReaderUnlock() { CERES_SAFE_PTHREAD(pthread_rwlock_unlock); }
247 #undef CERES_SAFE_PTHREAD
248
249 #elif defined(CERES_HAVE_PTHREAD)
250
251 #define CERES_SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */  \
252   if (is_safe_ && fncall(&mutex_) != 0) abort();                              \
253 } while (0)
254
255 Mutex::Mutex()             {
256   SetIsSafe();
257   if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
258 }
259 Mutex::~Mutex()            { CERES_SAFE_PTHREAD(pthread_mutex_destroy); }
260 void Mutex::Lock()         { CERES_SAFE_PTHREAD(pthread_mutex_lock); }
261 void Mutex::Unlock()       { CERES_SAFE_PTHREAD(pthread_mutex_unlock); }
262 #ifdef CERES_GMUTEX_TRYLOCK
263 bool Mutex::TryLock()      { return is_safe_ ?
264                                  pthread_mutex_trylock(&mutex_) == 0 : true; }
265 #endif
266 void Mutex::ReaderLock()   { Lock(); }
267 void Mutex::ReaderUnlock() { Unlock(); }
268 #undef CERES_SAFE_PTHREAD
269
270 #endif
271
272 // --------------------------------------------------------------------------
273 // Some helper classes
274
275 // Note: The weird "Ceres" prefix for the class is a workaround for having two
276 // similar mutex.h files included in the same translation unit. This is a
277 // problem because macros do not respect C++ namespaces, and as a result, this
278 // does not work well (e.g. inside Chrome). The offending macros are
279 // "MutexLock(x) COMPILE_ASSERT(false)". To work around this, "Ceres" is
280 // prefixed to the class names; this permits defining the classes.
281
282 // CeresMutexLock(mu) acquires mu when constructed and releases it
283 // when destroyed.
284 class CeresMutexLock {
285  public:
286   explicit CeresMutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); }
287   ~CeresMutexLock() { mu_->Unlock(); }
288  private:
289   Mutex * const mu_;
290   // Disallow "evil" constructors
291   CeresMutexLock(const CeresMutexLock&);
292   void operator=(const CeresMutexLock&);
293 };
294
295 // CeresReaderMutexLock and CeresWriterMutexLock do the same, for rwlocks
296 class CeresReaderMutexLock {
297  public:
298   explicit CeresReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); }
299   ~CeresReaderMutexLock() { mu_->ReaderUnlock(); }
300  private:
301   Mutex * const mu_;
302   // Disallow "evil" constructors
303   CeresReaderMutexLock(const CeresReaderMutexLock&);
304   void operator=(const CeresReaderMutexLock&);
305 };
306
307 class CeresWriterMutexLock {
308  public:
309   explicit CeresWriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); }
310   ~CeresWriterMutexLock() { mu_->WriterUnlock(); }
311  private:
312   Mutex * const mu_;
313   // Disallow "evil" constructors
314   CeresWriterMutexLock(const CeresWriterMutexLock&);
315   void operator=(const CeresWriterMutexLock&);
316 };
317
318 // Catch bug where variable name is omitted, e.g. MutexLock (&mu);
319 #define CeresMutexLock(x) \
320     COMPILE_ASSERT(0, ceres_mutex_lock_decl_missing_var_name)
321 #define CeresReaderMutexLock(x) \
322     COMPILE_ASSERT(0, ceres_rmutex_lock_decl_missing_var_name)
323 #define CeresWriterMutexLock(x) \
324     COMPILE_ASSERT(0, ceres_wmutex_lock_decl_missing_var_name)
325
326 }  // namespace internal
327 }  // namespace ceres
328
329 #endif  // CERES_INTERNAL_MUTEX_H_