Chris@47: // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors Chris@47: // Licensed under the MIT License: Chris@47: // Chris@47: // Permission is hereby granted, free of charge, to any person obtaining a copy Chris@47: // of this software and associated documentation files (the "Software"), to deal Chris@47: // in the Software without restriction, including without limitation the rights Chris@47: // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Chris@47: // copies of the Software, and to permit persons to whom the Software is Chris@47: // furnished to do so, subject to the following conditions: Chris@47: // Chris@47: // The above copyright notice and this permission notice shall be included in Chris@47: // all copies or substantial portions of the Software. Chris@47: // Chris@47: // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR Chris@47: // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, Chris@47: // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE Chris@47: // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER Chris@47: // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, Chris@47: // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN Chris@47: // THE SOFTWARE. Chris@47: Chris@47: #ifndef KJ_MUTEX_H_ Chris@47: #define KJ_MUTEX_H_ Chris@47: Chris@47: #if defined(__GNUC__) && !KJ_HEADER_WARNINGS Chris@47: #pragma GCC system_header Chris@47: #endif Chris@47: Chris@47: #include "memory.h" Chris@47: #include Chris@47: Chris@47: #if __linux__ && !defined(KJ_USE_FUTEX) Chris@47: #define KJ_USE_FUTEX 1 Chris@47: #endif Chris@47: Chris@47: #if !KJ_USE_FUTEX && !_WIN32 Chris@47: // On Linux we use futex. On other platforms we wrap pthreads. Chris@47: // TODO(someday): Write efficient low-level locking primitives for other platforms. Chris@47: #include Chris@47: #endif Chris@47: Chris@47: namespace kj { Chris@47: Chris@47: // ======================================================================================= Chris@47: // Private details -- public interfaces follow below. Chris@47: Chris@47: namespace _ { // private Chris@47: Chris@47: class Mutex { Chris@47: // Internal implementation details. See `MutexGuarded`. Chris@47: Chris@47: public: Chris@47: Mutex(); Chris@47: ~Mutex(); Chris@47: KJ_DISALLOW_COPY(Mutex); Chris@47: Chris@47: enum Exclusivity { Chris@47: EXCLUSIVE, Chris@47: SHARED Chris@47: }; Chris@47: Chris@47: void lock(Exclusivity exclusivity); Chris@47: void unlock(Exclusivity exclusivity); Chris@47: Chris@47: void assertLockedByCaller(Exclusivity exclusivity); Chris@47: // In debug mode, assert that the mutex is locked by the calling thread, or if that is Chris@47: // non-trivial, assert that the mutex is locked (which should be good enough to catch problems Chris@47: // in unit tests). In non-debug builds, do nothing. Chris@47: Chris@47: private: Chris@47: #if KJ_USE_FUTEX Chris@47: uint futex; Chris@47: // bit 31 (msb) = set if exclusive lock held Chris@47: // bit 30 (msb) = set if threads are waiting for exclusive lock Chris@47: // bits 0-29 = count of readers; If an exclusive lock is held, this is the count of threads Chris@47: // waiting for a read lock, otherwise it is the count of threads that currently hold a read Chris@47: // lock. Chris@47: Chris@47: static constexpr uint EXCLUSIVE_HELD = 1u << 31; Chris@47: static constexpr uint EXCLUSIVE_REQUESTED = 1u << 30; Chris@47: static constexpr uint SHARED_COUNT_MASK = EXCLUSIVE_REQUESTED - 1; Chris@47: Chris@47: #elif _WIN32 Chris@47: uintptr_t srwLock; // Actually an SRWLOCK, but don't want to #include in header. Chris@47: Chris@47: #else Chris@47: mutable pthread_rwlock_t mutex; Chris@47: #endif Chris@47: }; Chris@47: Chris@47: class Once { Chris@47: // Internal implementation details. See `Lazy`. Chris@47: Chris@47: public: Chris@47: #if KJ_USE_FUTEX Chris@47: inline Once(bool startInitialized = false) Chris@47: : futex(startInitialized ? INITIALIZED : UNINITIALIZED) {} Chris@47: #else Chris@47: Once(bool startInitialized = false); Chris@47: ~Once(); Chris@47: #endif Chris@47: KJ_DISALLOW_COPY(Once); Chris@47: Chris@47: class Initializer { Chris@47: public: Chris@47: virtual void run() = 0; Chris@47: }; Chris@47: Chris@47: void runOnce(Initializer& init); Chris@47: Chris@47: #if _WIN32 // TODO(perf): Can we make this inline on win32 somehow? Chris@47: bool isInitialized() noexcept; Chris@47: Chris@47: #else Chris@47: inline bool isInitialized() noexcept { Chris@47: // Fast path check to see if runOnce() would simply return immediately. Chris@47: #if KJ_USE_FUTEX Chris@47: return __atomic_load_n(&futex, __ATOMIC_ACQUIRE) == INITIALIZED; Chris@47: #else Chris@47: return __atomic_load_n(&state, __ATOMIC_ACQUIRE) == INITIALIZED; Chris@47: #endif Chris@47: } Chris@47: #endif Chris@47: Chris@47: void reset(); Chris@47: // Returns the state from initialized to uninitialized. It is an error to call this when Chris@47: // not already initialized, or when runOnce() or isInitialized() might be called concurrently in Chris@47: // another thread. Chris@47: Chris@47: private: Chris@47: #if KJ_USE_FUTEX Chris@47: uint futex; Chris@47: Chris@47: enum State { Chris@47: UNINITIALIZED, Chris@47: INITIALIZING, Chris@47: INITIALIZING_WITH_WAITERS, Chris@47: INITIALIZED Chris@47: }; Chris@47: Chris@47: #elif _WIN32 Chris@47: uintptr_t initOnce; // Actually an INIT_ONCE, but don't want to #include in header. Chris@47: Chris@47: #else Chris@47: enum State { Chris@47: UNINITIALIZED, Chris@47: INITIALIZED Chris@47: }; Chris@47: State state; Chris@47: pthread_mutex_t mutex; Chris@47: #endif Chris@47: }; Chris@47: Chris@47: } // namespace _ (private) Chris@47: Chris@47: // ======================================================================================= Chris@47: // Public interface Chris@47: Chris@47: template Chris@47: class Locked { Chris@47: // Return type for `MutexGuarded::lock()`. `Locked` provides access to the guarded object Chris@47: // and unlocks the mutex when it goes out of scope. Chris@47: Chris@47: public: Chris@47: KJ_DISALLOW_COPY(Locked); Chris@47: inline Locked(): mutex(nullptr), ptr(nullptr) {} Chris@47: inline Locked(Locked&& other): mutex(other.mutex), ptr(other.ptr) { Chris@47: other.mutex = nullptr; Chris@47: other.ptr = nullptr; Chris@47: } Chris@47: inline ~Locked() { Chris@47: if (mutex != nullptr) mutex->unlock(isConst() ? _::Mutex::SHARED : _::Mutex::EXCLUSIVE); Chris@47: } Chris@47: Chris@47: inline Locked& operator=(Locked&& other) { Chris@47: if (mutex != nullptr) mutex->unlock(isConst() ? _::Mutex::SHARED : _::Mutex::EXCLUSIVE); Chris@47: mutex = other.mutex; Chris@47: ptr = other.ptr; Chris@47: other.mutex = nullptr; Chris@47: other.ptr = nullptr; Chris@47: return *this; Chris@47: } Chris@47: Chris@47: inline void release() { Chris@47: if (mutex != nullptr) mutex->unlock(isConst() ? _::Mutex::SHARED : _::Mutex::EXCLUSIVE); Chris@47: mutex = nullptr; Chris@47: ptr = nullptr; Chris@47: } Chris@47: Chris@47: inline T* operator->() { return ptr; } Chris@47: inline const T* operator->() const { return ptr; } Chris@47: inline T& operator*() { return *ptr; } Chris@47: inline const T& operator*() const { return *ptr; } Chris@47: inline T* get() { return ptr; } Chris@47: inline const T* get() const { return ptr; } Chris@47: inline operator T*() { return ptr; } Chris@47: inline operator const T*() const { return ptr; } Chris@47: Chris@47: private: Chris@47: _::Mutex* mutex; Chris@47: T* ptr; Chris@47: Chris@47: inline Locked(_::Mutex& mutex, T& value): mutex(&mutex), ptr(&value) {} Chris@47: Chris@47: template Chris@47: friend class MutexGuarded; Chris@47: }; Chris@47: Chris@47: template Chris@47: class MutexGuarded { Chris@47: // An object of type T, guarded by a mutex. In order to access the object, you must lock it. Chris@47: // Chris@47: // Write locks are not "recursive" -- trying to lock again in a thread that already holds a lock Chris@47: // will deadlock. Recursive write locks are usually a sign of bad design. Chris@47: // Chris@47: // Unfortunately, **READ LOCKS ARE NOT RECURSIVE** either. Common sense says they should be. Chris@47: // But on many operating systems (BSD, OSX), recursively read-locking a pthread_rwlock is Chris@47: // actually unsafe. The problem is that writers are "prioritized" over readers, so a read lock Chris@47: // request will block if any write lock requests are outstanding. So, if thread A takes a read Chris@47: // lock, thread B requests a write lock (and starts waiting), and then thread A tries to take Chris@47: // another read lock recursively, the result is deadlock. Chris@47: Chris@47: public: Chris@47: template Chris@47: explicit MutexGuarded(Params&&... params); Chris@47: // Initialize the mutex-guarded object by passing the given parameters to its constructor. Chris@47: Chris@47: Locked lockExclusive() const; Chris@47: // Exclusively locks the object and returns it. The returned `Locked` can be passed by Chris@47: // move, similar to `Own`. Chris@47: // Chris@47: // This method is declared `const` in accordance with KJ style rules which say that constness Chris@47: // should be used to indicate thread-safety. It is safe to share a const pointer between threads, Chris@47: // but it is not safe to share a mutable pointer. Since the whole point of MutexGuarded is to Chris@47: // be shared between threads, its methods should be const, even though locking it produces a Chris@47: // non-const pointer to the contained object. Chris@47: Chris@47: Locked lockShared() const; Chris@47: // Lock the value for shared access. Multiple shared locks can be taken concurrently, but cannot Chris@47: // be held at the same time as a non-shared lock. Chris@47: Chris@47: inline const T& getWithoutLock() const { return value; } Chris@47: inline T& getWithoutLock() { return value; } Chris@47: // Escape hatch for cases where some external factor guarantees that it's safe to get the Chris@47: // value. You should treat these like const_cast -- be highly suspicious of any use. Chris@47: Chris@47: inline const T& getAlreadyLockedShared() const; Chris@47: inline T& getAlreadyLockedShared(); Chris@47: inline T& getAlreadyLockedExclusive() const; Chris@47: // Like `getWithoutLock()`, but asserts that the lock is already held by the calling thread. Chris@47: Chris@47: private: Chris@47: mutable _::Mutex mutex; Chris@47: mutable T value; Chris@47: }; Chris@47: Chris@47: template Chris@47: class MutexGuarded { Chris@47: // MutexGuarded cannot guard a const type. This would be pointless anyway, and would complicate Chris@47: // the implementation of Locked, which uses constness to decide what kind of lock it holds. Chris@47: static_assert(sizeof(T) < 0, "MutexGuarded's type cannot be const."); Chris@47: }; Chris@47: Chris@47: template Chris@47: class Lazy { Chris@47: // A lazily-initialized value. Chris@47: Chris@47: public: Chris@47: template Chris@47: T& get(Func&& init); Chris@47: template Chris@47: const T& get(Func&& init) const; Chris@47: // The first thread to call get() will invoke the given init function to construct the value. Chris@47: // Other threads will block until construction completes, then return the same value. Chris@47: // Chris@47: // `init` is a functor(typically a lambda) which takes `SpaceFor&` as its parameter and returns Chris@47: // `Own`. If `init` throws an exception, the exception is propagated out of that thread's Chris@47: // call to `get()`, and subsequent calls behave as if `get()` hadn't been called at all yet -- Chris@47: // in other words, subsequent calls retry initialization until it succeeds. Chris@47: Chris@47: private: Chris@47: mutable _::Once once; Chris@47: mutable SpaceFor space; Chris@47: mutable Own value; Chris@47: Chris@47: template Chris@47: class InitImpl; Chris@47: }; Chris@47: Chris@47: // ======================================================================================= Chris@47: // Inline implementation details Chris@47: Chris@47: template Chris@47: template Chris@47: inline MutexGuarded::MutexGuarded(Params&&... params) Chris@47: : value(kj::fwd(params)...) {} Chris@47: Chris@47: template Chris@47: inline Locked MutexGuarded::lockExclusive() const { Chris@47: mutex.lock(_::Mutex::EXCLUSIVE); Chris@47: return Locked(mutex, value); Chris@47: } Chris@47: Chris@47: template Chris@47: inline Locked MutexGuarded::lockShared() const { Chris@47: mutex.lock(_::Mutex::SHARED); Chris@47: return Locked(mutex, value); Chris@47: } Chris@47: Chris@47: template Chris@47: inline const T& MutexGuarded::getAlreadyLockedShared() const { Chris@47: #ifdef KJ_DEBUG Chris@47: mutex.assertLockedByCaller(_::Mutex::SHARED); Chris@47: #endif Chris@47: return value; Chris@47: } Chris@47: template Chris@47: inline T& MutexGuarded::getAlreadyLockedShared() { Chris@47: #ifdef KJ_DEBUG Chris@47: mutex.assertLockedByCaller(_::Mutex::SHARED); Chris@47: #endif Chris@47: return value; Chris@47: } Chris@47: template Chris@47: inline T& MutexGuarded::getAlreadyLockedExclusive() const { Chris@47: #ifdef KJ_DEBUG Chris@47: mutex.assertLockedByCaller(_::Mutex::EXCLUSIVE); Chris@47: #endif Chris@47: return const_cast(value); Chris@47: } Chris@47: Chris@47: template Chris@47: template Chris@47: class Lazy::InitImpl: public _::Once::Initializer { Chris@47: public: Chris@47: inline InitImpl(const Lazy& lazy, Func&& func): lazy(lazy), func(kj::fwd(func)) {} Chris@47: Chris@47: void run() override { Chris@47: lazy.value = func(lazy.space); Chris@47: } Chris@47: Chris@47: private: Chris@47: const Lazy& lazy; Chris@47: Func func; Chris@47: }; Chris@47: Chris@47: template Chris@47: template Chris@47: inline T& Lazy::get(Func&& init) { Chris@47: if (!once.isInitialized()) { Chris@47: InitImpl initImpl(*this, kj::fwd(init)); Chris@47: once.runOnce(initImpl); Chris@47: } Chris@47: return *value; Chris@47: } Chris@47: Chris@47: template Chris@47: template Chris@47: inline const T& Lazy::get(Func&& init) const { Chris@47: if (!once.isInitialized()) { Chris@47: InitImpl initImpl(*this, kj::fwd(init)); Chris@47: once.runOnce(initImpl); Chris@47: } Chris@47: return *value; Chris@47: } Chris@47: Chris@47: } // namespace kj Chris@47: Chris@47: #endif // KJ_MUTEX_H_