Blame internal/ceres/mutex.h

Packit ea1746
// Ceres Solver - A fast non-linear least squares minimizer
Packit ea1746
// Copyright 2015 Google Inc. All rights reserved.
Packit ea1746
// http://ceres-solver.org/
Packit ea1746
//
Packit ea1746
// Redistribution and use in source and binary forms, with or without
Packit ea1746
// modification, are permitted provided that the following conditions are met:
Packit ea1746
//
Packit ea1746
// * Redistributions of source code must retain the above copyright notice,
Packit ea1746
//   this list of conditions and the following disclaimer.
Packit ea1746
// * Redistributions in binary form must reproduce the above copyright notice,
Packit ea1746
//   this list of conditions and the following disclaimer in the documentation
Packit ea1746
//   and/or other materials provided with the distribution.
Packit ea1746
// * Neither the name of Google Inc. nor the names of its contributors may be
Packit ea1746
//   used to endorse or promote products derived from this software without
Packit ea1746
//   specific prior written permission.
Packit ea1746
//
Packit ea1746
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
Packit ea1746
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
Packit ea1746
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
Packit ea1746
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
Packit ea1746
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
Packit ea1746
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
Packit ea1746
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
Packit ea1746
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
Packit ea1746
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
Packit ea1746
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
Packit ea1746
// POSSIBILITY OF SUCH DAMAGE.
Packit ea1746
//
Packit ea1746
// Author: Craig Silverstein.
Packit ea1746
//
Packit ea1746
// A simple mutex wrapper, supporting locks and read-write locks.
Packit ea1746
// You should assume the locks are *not* re-entrant.
Packit ea1746
//
Packit ea1746
// This class is meant to be internal-only and should be wrapped by an
Packit ea1746
// internal namespace.  Before you use this module, please give the
Packit ea1746
// name of your internal namespace for this module.  Or, if you want
Packit ea1746
// to expose it, you'll want to move it to the Google namespace.  We
Packit ea1746
// cannot put this class in global namespace because there can be some
Packit ea1746
// problems when we have multiple versions of Mutex in each shared object.
Packit ea1746
//
Packit ea1746
// NOTE: by default, we have #ifdef'ed out the TryLock() method.
Packit ea1746
//       This is for two reasons:
Packit ea1746
// 1) TryLock() under Windows is a bit annoying (it requires a
Packit ea1746
//    #define to be defined very early).
Packit ea1746
// 2) TryLock() is broken for NO_THREADS mode, at least in NDEBUG
Packit ea1746
//    mode.
Packit ea1746
// If you need TryLock(), and either these two caveats are not a
Packit ea1746
// problem for you, or you're willing to work around them, then
Packit ea1746
// feel free to #define GMUTEX_TRYLOCK, or to remove the #ifdefs
Packit ea1746
// in the code below.
Packit ea1746
//
Packit ea1746
// CYGWIN NOTE: Cygwin support for rwlock seems to be buggy:
Packit ea1746
//    http://www.cygwin.com/ml/cygwin/2008-12/msg00017.html
Packit ea1746
// Because of that, we might as well use windows locks for
Packit ea1746
// cygwin.  They seem to be more reliable than the cygwin pthreads layer.
Packit ea1746
//
Packit ea1746
// TRICKY IMPLEMENTATION NOTE:
Packit ea1746
// This class is designed to be safe to use during
Packit ea1746
// dynamic-initialization -- that is, by global constructors that are
Packit ea1746
// run before main() starts.  The issue in this case is that
Packit ea1746
// dynamic-initialization happens in an unpredictable order, and it
Packit ea1746
// could be that someone else's dynamic initializer could call a
Packit ea1746
// function that tries to acquire this mutex -- but that all happens
Packit ea1746
// before this mutex's constructor has run.  (This can happen even if
Packit ea1746
// the mutex and the function that uses the mutex are in the same .cc
Packit ea1746
// file.)  Basically, because Mutex does non-trivial work in its
Packit ea1746
// constructor, it's not, in the naive implementation, safe to use
Packit ea1746
// before dynamic initialization has run on it.
Packit ea1746
//
Packit ea1746
// The solution used here is to pair the actual mutex primitive with a
Packit ea1746
// bool that is set to true when the mutex is dynamically initialized.
Packit ea1746
// (Before that it's false.)  Then we modify all mutex routines to
Packit ea1746
// look at the bool, and not try to lock/unlock until the bool makes
Packit ea1746
// it to true (which happens after the Mutex constructor has run.)
Packit ea1746
//
Packit ea1746
// This works because before main() starts -- particularly, during
Packit ea1746
// dynamic initialization -- there are no threads, so a) it's ok that
Packit ea1746
// the mutex operations are a no-op, since we don't need locking then
Packit ea1746
// anyway; and b) we can be quite confident our bool won't change
Packit ea1746
// state between a call to Lock() and a call to Unlock() (that would
Packit ea1746
// require a global constructor in one translation unit to call Lock()
Packit ea1746
// and another global constructor in another translation unit to call
Packit ea1746
// Unlock() later, which is pretty perverse).
Packit ea1746
//
Packit ea1746
// That said, it's tricky, and can conceivably fail; it's safest to
Packit ea1746
// avoid trying to acquire a mutex in a global constructor, if you
Packit ea1746
// can.  One way it can fail is that a really smart compiler might
Packit ea1746
// initialize the bool to true at static-initialization time (too
Packit ea1746
// early) rather than at dynamic-initialization time.  To discourage
Packit ea1746
// that, we set is_safe_ to true in code (not the constructor
Packit ea1746
// colon-initializer) and set it to true via a function that always
Packit ea1746
// evaluates to true, but that the compiler can't know always
Packit ea1746
// evaluates to true.  This should be good enough.
Packit ea1746
Packit ea1746
#ifndef CERES_INTERNAL_MUTEX_H_
Packit ea1746
#define CERES_INTERNAL_MUTEX_H_
Packit ea1746
Packit ea1746
#include "ceres/internal/port.h"
Packit ea1746
Packit ea1746
#if defined(CERES_NO_THREADS)
Packit ea1746
  typedef int MutexType;      // to keep a lock-count
Packit ea1746
#elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
Packit ea1746
# define CERES_WIN32_LEAN_AND_MEAN  // We only need minimal includes
Packit ea1746
# ifdef CERES_GMUTEX_TRYLOCK
Packit ea1746
  // We need Windows NT or later for TryEnterCriticalSection().  If you
Packit ea1746
  // don't need that functionality, you can remove these _WIN32_WINNT
Packit ea1746
  // lines, and change TryLock() to assert(0) or something.
Packit ea1746
#   ifndef _WIN32_WINNT
Packit ea1746
#     define _WIN32_WINNT 0x0400
Packit ea1746
#   endif
Packit ea1746
# endif
Packit ea1746
// Unfortunately, windows.h defines a bunch of macros with common
Packit ea1746
// names. Two in particular need avoiding: ERROR and min/max.
Packit ea1746
// To avoid macro definition of ERROR.
Packit ea1746
# define NOGDI
Packit ea1746
// To avoid macro definition of min/max.
Packit ea1746
# ifndef NOMINMAX
Packit ea1746
#   define NOMINMAX
Packit ea1746
# endif
Packit ea1746
# include <windows.h>
Packit ea1746
  typedef CRITICAL_SECTION MutexType;
Packit ea1746
#elif defined(CERES_HAVE_PTHREAD) && defined(CERES_HAVE_RWLOCK)
Packit ea1746
  // Needed for pthread_rwlock_*.  If it causes problems, you could take it
Packit ea1746
  // out, but then you'd have to unset CERES_HAVE_RWLOCK (at least on linux --
Packit ea1746
  // it *does* cause problems for FreeBSD, or MacOSX, but isn't needed for
Packit ea1746
  // locking there.)
Packit ea1746
# if defined(__linux__) && !defined(_XOPEN_SOURCE)
Packit ea1746
#   define _XOPEN_SOURCE 500  // may be needed to get the rwlock calls
Packit ea1746
# endif
Packit ea1746
# include <pthread.h>
Packit ea1746
  typedef pthread_rwlock_t MutexType;
Packit ea1746
#elif defined(CERES_HAVE_PTHREAD)
Packit ea1746
# include <pthread.h>
Packit ea1746
  typedef pthread_mutex_t MutexType;
Packit ea1746
#else
Packit ea1746
# error Need to implement mutex.h for your architecture, or #define NO_THREADS
Packit ea1746
#endif
Packit ea1746
Packit ea1746
// We need to include these header files after defining _XOPEN_SOURCE
Packit ea1746
// as they may define the _XOPEN_SOURCE macro.
Packit ea1746
#include <assert.h>
Packit ea1746
#include <stdlib.h>      // for abort()
Packit ea1746
Packit ea1746
namespace ceres {
Packit ea1746
namespace internal {
Packit ea1746
Packit ea1746
class Mutex {
Packit ea1746
 public:
Packit ea1746
  // Create a Mutex that is not held by anybody.  This constructor is
Packit ea1746
  // typically used for Mutexes allocated on the heap or the stack.
Packit ea1746
  // See below for a recommendation for constructing global Mutex
Packit ea1746
  // objects.
Packit ea1746
  inline Mutex();
Packit ea1746
Packit ea1746
  // Destructor
Packit ea1746
  inline ~Mutex();
Packit ea1746
Packit ea1746
  inline void Lock();    // Block if needed until free then acquire exclusively
Packit ea1746
  inline void Unlock();  // Release a lock acquired via Lock()
Packit ea1746
#ifdef CERES_GMUTEX_TRYLOCK
Packit ea1746
  inline bool TryLock(); // If free, Lock() and return true, else return false
Packit ea1746
#endif
Packit ea1746
  // Note that on systems that don't support read-write locks, these may
Packit ea1746
  // be implemented as synonyms to Lock() and Unlock().  So you can use
Packit ea1746
  // these for efficiency, but don't use them anyplace where being able
Packit ea1746
  // to do shared reads is necessary to avoid deadlock.
Packit ea1746
  inline void ReaderLock();   // Block until free or shared then acquire a share
Packit ea1746
  inline void ReaderUnlock(); // Release a read share of this Mutex
Packit ea1746
  inline void WriterLock() { Lock(); }     // Acquire an exclusive lock
Packit ea1746
  inline void WriterUnlock() { Unlock(); } // Release a lock from WriterLock()
Packit ea1746
Packit ea1746
  // TODO(hamaji): Do nothing, implement correctly.
Packit ea1746
  inline void AssertHeld() {}
Packit ea1746
Packit ea1746
 private:
Packit ea1746
  MutexType mutex_;
Packit ea1746
  // We want to make sure that the compiler sets is_safe_ to true only
Packit ea1746
  // when we tell it to, and never makes assumptions is_safe_ is
Packit ea1746
  // always true.  volatile is the most reliable way to do that.
Packit ea1746
  volatile bool is_safe_;
Packit ea1746
Packit ea1746
  inline void SetIsSafe() { is_safe_ = true; }
Packit ea1746
Packit ea1746
  // Catch the error of writing Mutex when intending MutexLock.
Packit ea1746
  Mutex(Mutex* /*ignored*/) {}
Packit ea1746
  // Disallow "evil" constructors
Packit ea1746
  Mutex(const Mutex&);
Packit ea1746
  void operator=(const Mutex&);
Packit ea1746
};
Packit ea1746
Packit ea1746
// Now the implementation of Mutex for various systems
Packit ea1746
#if defined(CERES_NO_THREADS)
Packit ea1746
Packit ea1746
// When we don't have threads, we can be either reading or writing,
Packit ea1746
// but not both.  We can have lots of readers at once (in no-threads
Packit ea1746
// mode, that's most likely to happen in recursive function calls),
Packit ea1746
// but only one writer.  We represent this by having mutex_ be -1 when
Packit ea1746
// writing and a number > 0 when reading (and 0 when no lock is held).
Packit ea1746
//
Packit ea1746
// In debug mode, we assert these invariants, while in non-debug mode
Packit ea1746
// we do nothing, for efficiency.  That's why everything is in an
Packit ea1746
// assert.
Packit ea1746
Packit ea1746
Mutex::Mutex() : mutex_(0) { }
Packit ea1746
Mutex::~Mutex()            { assert(mutex_ == 0); }
Packit ea1746
void Mutex::Lock()         { assert(--mutex_ == -1); }
Packit ea1746
void Mutex::Unlock()       { assert(mutex_++ == -1); }
Packit ea1746
#ifdef CERES_GMUTEX_TRYLOCK
Packit ea1746
bool Mutex::TryLock()      { if (mutex_) return false; Lock(); return true; }
Packit ea1746
#endif
Packit ea1746
void Mutex::ReaderLock()   { assert(++mutex_ > 0); }
Packit ea1746
void Mutex::ReaderUnlock() { assert(mutex_-- > 0); }
Packit ea1746
Packit ea1746
#elif defined(_WIN32) || defined(__CYGWIN32__) || defined(__CYGWIN64__)
Packit ea1746
Packit ea1746
Mutex::Mutex()             { InitializeCriticalSection(&mutex_); SetIsSafe(); }
Packit ea1746
Mutex::~Mutex()            { DeleteCriticalSection(&mutex_); }
Packit ea1746
void Mutex::Lock()         { if (is_safe_) EnterCriticalSection(&mutex_); }
Packit ea1746
void Mutex::Unlock()       { if (is_safe_) LeaveCriticalSection(&mutex_); }
Packit ea1746
#ifdef GMUTEX_TRYLOCK
Packit ea1746
bool Mutex::TryLock()      { return is_safe_ ?
Packit ea1746
                                 TryEnterCriticalSection(&mutex_) != 0 : true; }
Packit ea1746
#endif
Packit ea1746
void Mutex::ReaderLock()   { Lock(); }      // we don't have read-write locks
Packit ea1746
void Mutex::ReaderUnlock() { Unlock(); }
Packit ea1746
Packit ea1746
#elif defined(CERES_HAVE_PTHREAD) && defined(CERES_HAVE_RWLOCK)
Packit ea1746
Packit ea1746
#define CERES_SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */ \
Packit ea1746
  if (is_safe_ && fncall(&mutex_) != 0) abort();                             \
Packit ea1746
} while (0)
Packit ea1746
Packit ea1746
Mutex::Mutex() {
Packit ea1746
  SetIsSafe();
Packit ea1746
  if (is_safe_ && pthread_rwlock_init(&mutex_, NULL) != 0) abort();
Packit ea1746
}
Packit ea1746
Mutex::~Mutex()            { CERES_SAFE_PTHREAD(pthread_rwlock_destroy); }
Packit ea1746
void Mutex::Lock()         { CERES_SAFE_PTHREAD(pthread_rwlock_wrlock); }
Packit ea1746
void Mutex::Unlock()       { CERES_SAFE_PTHREAD(pthread_rwlock_unlock); }
Packit ea1746
#ifdef CERES_GMUTEX_TRYLOCK
Packit ea1746
bool Mutex::TryLock()      { return is_safe_ ?
Packit ea1746
                                    pthread_rwlock_trywrlock(&mutex_) == 0 :
Packit ea1746
                                    true; }
Packit ea1746
#endif
Packit ea1746
void Mutex::ReaderLock()   { CERES_SAFE_PTHREAD(pthread_rwlock_rdlock); }
Packit ea1746
void Mutex::ReaderUnlock() { CERES_SAFE_PTHREAD(pthread_rwlock_unlock); }
Packit ea1746
#undef CERES_SAFE_PTHREAD
Packit ea1746
Packit ea1746
#elif defined(CERES_HAVE_PTHREAD)
Packit ea1746
Packit ea1746
#define CERES_SAFE_PTHREAD(fncall) do { /* run fncall if is_safe_ is true */  \
Packit ea1746
  if (is_safe_ && fncall(&mutex_) != 0) abort();                              \
Packit ea1746
} while (0)
Packit ea1746
Packit ea1746
Mutex::Mutex()             {
Packit ea1746
  SetIsSafe();
Packit ea1746
  if (is_safe_ && pthread_mutex_init(&mutex_, NULL) != 0) abort();
Packit ea1746
}
Packit ea1746
Mutex::~Mutex()            { CERES_SAFE_PTHREAD(pthread_mutex_destroy); }
Packit ea1746
void Mutex::Lock()         { CERES_SAFE_PTHREAD(pthread_mutex_lock); }
Packit ea1746
void Mutex::Unlock()       { CERES_SAFE_PTHREAD(pthread_mutex_unlock); }
Packit ea1746
#ifdef CERES_GMUTEX_TRYLOCK
Packit ea1746
bool Mutex::TryLock()      { return is_safe_ ?
Packit ea1746
                                 pthread_mutex_trylock(&mutex_) == 0 : true; }
Packit ea1746
#endif
Packit ea1746
void Mutex::ReaderLock()   { Lock(); }
Packit ea1746
void Mutex::ReaderUnlock() { Unlock(); }
Packit ea1746
#undef CERES_SAFE_PTHREAD
Packit ea1746
Packit ea1746
#endif
Packit ea1746
Packit ea1746
// --------------------------------------------------------------------------
Packit ea1746
// Some helper classes
Packit ea1746
Packit ea1746
// Note: The weird "Ceres" prefix for the class is a workaround for having two
Packit ea1746
// similar mutex.h files included in the same translation unit. This is a
Packit ea1746
// problem because macros do not respect C++ namespaces, and as a result, this
Packit ea1746
// does not work well (e.g. inside Chrome). The offending macros are
Packit ea1746
// "MutexLock(x) COMPILE_ASSERT(false)". To work around this, "Ceres" is
Packit ea1746
// prefixed to the class names; this permits defining the classes.
Packit ea1746
Packit ea1746
// CeresMutexLock(mu) acquires mu when constructed and releases it
Packit ea1746
// when destroyed.
Packit ea1746
class CeresMutexLock {
Packit ea1746
 public:
Packit ea1746
  explicit CeresMutexLock(Mutex *mu) : mu_(mu) { mu_->Lock(); }
Packit ea1746
  ~CeresMutexLock() { mu_->Unlock(); }
Packit ea1746
 private:
Packit ea1746
  Mutex * const mu_;
Packit ea1746
  // Disallow "evil" constructors
Packit ea1746
  CeresMutexLock(const CeresMutexLock&);
Packit ea1746
  void operator=(const CeresMutexLock&);
Packit ea1746
};
Packit ea1746
Packit ea1746
// CeresReaderMutexLock and CeresWriterMutexLock do the same, for rwlocks
Packit ea1746
class CeresReaderMutexLock {
Packit ea1746
 public:
Packit ea1746
  explicit CeresReaderMutexLock(Mutex *mu) : mu_(mu) { mu_->ReaderLock(); }
Packit ea1746
  ~CeresReaderMutexLock() { mu_->ReaderUnlock(); }
Packit ea1746
 private:
Packit ea1746
  Mutex * const mu_;
Packit ea1746
  // Disallow "evil" constructors
Packit ea1746
  CeresReaderMutexLock(const CeresReaderMutexLock&);
Packit ea1746
  void operator=(const CeresReaderMutexLock&);
Packit ea1746
};
Packit ea1746
Packit ea1746
class CeresWriterMutexLock {
Packit ea1746
 public:
Packit ea1746
  explicit CeresWriterMutexLock(Mutex *mu) : mu_(mu) { mu_->WriterLock(); }
Packit ea1746
  ~CeresWriterMutexLock() { mu_->WriterUnlock(); }
Packit ea1746
 private:
Packit ea1746
  Mutex * const mu_;
Packit ea1746
  // Disallow "evil" constructors
Packit ea1746
  CeresWriterMutexLock(const CeresWriterMutexLock&);
Packit ea1746
  void operator=(const CeresWriterMutexLock&);
Packit ea1746
};
Packit ea1746
Packit ea1746
// Catch bug where variable name is omitted, e.g. MutexLock (&mu);
Packit ea1746
#define CeresMutexLock(x) \
Packit ea1746
    COMPILE_ASSERT(0, ceres_mutex_lock_decl_missing_var_name)
Packit ea1746
#define CeresReaderMutexLock(x) \
Packit ea1746
    COMPILE_ASSERT(0, ceres_rmutex_lock_decl_missing_var_name)
Packit ea1746
#define CeresWriterMutexLock(x) \
Packit ea1746
    COMPILE_ASSERT(0, ceres_wmutex_lock_decl_missing_var_name)
Packit ea1746
Packit ea1746
}  // namespace internal
Packit ea1746
}  // namespace ceres
Packit ea1746
Packit ea1746
#endif  // CERES_INTERNAL_MUTEX_H_