annotate win32-mingw/include/kj/mutex.h @ 140:59a8758c56b1

Add source for PortAudio stable v190600_20161030
author Chris Cannam <cannam@all-day-breakfast.com>
date Tue, 03 Jan 2017 13:44:07 +0000
parents 38d1c0e7850b
children eccd51b72864
rev   line source
cannam@135 1 // Copyright (c) 2013-2014 Sandstorm Development Group, Inc. and contributors
cannam@135 2 // Licensed under the MIT License:
cannam@135 3 //
cannam@135 4 // Permission is hereby granted, free of charge, to any person obtaining a copy
cannam@135 5 // of this software and associated documentation files (the "Software"), to deal
cannam@135 6 // in the Software without restriction, including without limitation the rights
cannam@135 7 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
cannam@135 8 // copies of the Software, and to permit persons to whom the Software is
cannam@135 9 // furnished to do so, subject to the following conditions:
cannam@135 10 //
cannam@135 11 // The above copyright notice and this permission notice shall be included in
cannam@135 12 // all copies or substantial portions of the Software.
cannam@135 13 //
cannam@135 14 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
cannam@135 15 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
cannam@135 16 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
cannam@135 17 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
cannam@135 18 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
cannam@135 19 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
cannam@135 20 // THE SOFTWARE.
cannam@135 21
cannam@135 22 #ifndef KJ_MUTEX_H_
cannam@135 23 #define KJ_MUTEX_H_
cannam@135 24
cannam@135 25 #if defined(__GNUC__) && !KJ_HEADER_WARNINGS
cannam@135 26 #pragma GCC system_header
cannam@135 27 #endif
cannam@135 28
cannam@135 29 #include "memory.h"
cannam@135 30 #include <inttypes.h>
cannam@135 31
cannam@135 32 #if __linux__ && !defined(KJ_USE_FUTEX)
cannam@135 33 #define KJ_USE_FUTEX 1
cannam@135 34 #endif
cannam@135 35
cannam@135 36 #if !KJ_USE_FUTEX && !_WIN32
cannam@135 37 // On Linux we use futex. On other platforms we wrap pthreads.
cannam@135 38 // TODO(someday): Write efficient low-level locking primitives for other platforms.
cannam@135 39 #include <pthread.h>
cannam@135 40 #endif
cannam@135 41
cannam@135 42 namespace kj {
cannam@135 43
cannam@135 44 // =======================================================================================
cannam@135 45 // Private details -- public interfaces follow below.
cannam@135 46
cannam@135 47 namespace _ { // private
cannam@135 48
cannam@135 49 class Mutex {
cannam@135 50 // Internal implementation details. See `MutexGuarded<T>`.
cannam@135 51
cannam@135 52 public:
cannam@135 53 Mutex();
cannam@135 54 ~Mutex();
cannam@135 55 KJ_DISALLOW_COPY(Mutex);
cannam@135 56
cannam@135 57 enum Exclusivity {
cannam@135 58 EXCLUSIVE,
cannam@135 59 SHARED
cannam@135 60 };
cannam@135 61
cannam@135 62 void lock(Exclusivity exclusivity);
cannam@135 63 void unlock(Exclusivity exclusivity);
cannam@135 64
cannam@135 65 void assertLockedByCaller(Exclusivity exclusivity);
cannam@135 66 // In debug mode, assert that the mutex is locked by the calling thread, or if that is
cannam@135 67 // non-trivial, assert that the mutex is locked (which should be good enough to catch problems
cannam@135 68 // in unit tests). In non-debug builds, do nothing.
cannam@135 69
cannam@135 70 private:
cannam@135 71 #if KJ_USE_FUTEX
cannam@135 72 uint futex;
cannam@135 73 // bit 31 (msb) = set if exclusive lock held
cannam@135 74 // bit 30 (msb) = set if threads are waiting for exclusive lock
cannam@135 75 // bits 0-29 = count of readers; If an exclusive lock is held, this is the count of threads
cannam@135 76 // waiting for a read lock, otherwise it is the count of threads that currently hold a read
cannam@135 77 // lock.
cannam@135 78
cannam@135 79 static constexpr uint EXCLUSIVE_HELD = 1u << 31;
cannam@135 80 static constexpr uint EXCLUSIVE_REQUESTED = 1u << 30;
cannam@135 81 static constexpr uint SHARED_COUNT_MASK = EXCLUSIVE_REQUESTED - 1;
cannam@135 82
cannam@135 83 #elif _WIN32
cannam@135 84 uintptr_t srwLock; // Actually an SRWLOCK, but don't want to #include <windows.h> in header.
cannam@135 85
cannam@135 86 #else
cannam@135 87 mutable pthread_rwlock_t mutex;
cannam@135 88 #endif
cannam@135 89 };
cannam@135 90
cannam@135 91 class Once {
cannam@135 92 // Internal implementation details. See `Lazy<T>`.
cannam@135 93
cannam@135 94 public:
cannam@135 95 #if KJ_USE_FUTEX
cannam@135 96 inline Once(bool startInitialized = false)
cannam@135 97 : futex(startInitialized ? INITIALIZED : UNINITIALIZED) {}
cannam@135 98 #else
cannam@135 99 Once(bool startInitialized = false);
cannam@135 100 ~Once();
cannam@135 101 #endif
cannam@135 102 KJ_DISALLOW_COPY(Once);
cannam@135 103
cannam@135 104 class Initializer {
cannam@135 105 public:
cannam@135 106 virtual void run() = 0;
cannam@135 107 };
cannam@135 108
cannam@135 109 void runOnce(Initializer& init);
cannam@135 110
cannam@135 111 #if _WIN32 // TODO(perf): Can we make this inline on win32 somehow?
cannam@135 112 bool isInitialized() noexcept;
cannam@135 113
cannam@135 114 #else
cannam@135 115 inline bool isInitialized() noexcept {
cannam@135 116 // Fast path check to see if runOnce() would simply return immediately.
cannam@135 117 #if KJ_USE_FUTEX
cannam@135 118 return __atomic_load_n(&futex, __ATOMIC_ACQUIRE) == INITIALIZED;
cannam@135 119 #else
cannam@135 120 return __atomic_load_n(&state, __ATOMIC_ACQUIRE) == INITIALIZED;
cannam@135 121 #endif
cannam@135 122 }
cannam@135 123 #endif
cannam@135 124
cannam@135 125 void reset();
cannam@135 126 // Returns the state from initialized to uninitialized. It is an error to call this when
cannam@135 127 // not already initialized, or when runOnce() or isInitialized() might be called concurrently in
cannam@135 128 // another thread.
cannam@135 129
cannam@135 130 private:
cannam@135 131 #if KJ_USE_FUTEX
cannam@135 132 uint futex;
cannam@135 133
cannam@135 134 enum State {
cannam@135 135 UNINITIALIZED,
cannam@135 136 INITIALIZING,
cannam@135 137 INITIALIZING_WITH_WAITERS,
cannam@135 138 INITIALIZED
cannam@135 139 };
cannam@135 140
cannam@135 141 #elif _WIN32
cannam@135 142 uintptr_t initOnce; // Actually an INIT_ONCE, but don't want to #include <windows.h> in header.
cannam@135 143
cannam@135 144 #else
cannam@135 145 enum State {
cannam@135 146 UNINITIALIZED,
cannam@135 147 INITIALIZED
cannam@135 148 };
cannam@135 149 State state;
cannam@135 150 pthread_mutex_t mutex;
cannam@135 151 #endif
cannam@135 152 };
cannam@135 153
cannam@135 154 } // namespace _ (private)
cannam@135 155
cannam@135 156 // =======================================================================================
cannam@135 157 // Public interface
cannam@135 158
cannam@135 159 template <typename T>
cannam@135 160 class Locked {
cannam@135 161 // Return type for `MutexGuarded<T>::lock()`. `Locked<T>` provides access to the guarded object
cannam@135 162 // and unlocks the mutex when it goes out of scope.
cannam@135 163
cannam@135 164 public:
cannam@135 165 KJ_DISALLOW_COPY(Locked);
cannam@135 166 inline Locked(): mutex(nullptr), ptr(nullptr) {}
cannam@135 167 inline Locked(Locked&& other): mutex(other.mutex), ptr(other.ptr) {
cannam@135 168 other.mutex = nullptr;
cannam@135 169 other.ptr = nullptr;
cannam@135 170 }
cannam@135 171 inline ~Locked() {
cannam@135 172 if (mutex != nullptr) mutex->unlock(isConst<T>() ? _::Mutex::SHARED : _::Mutex::EXCLUSIVE);
cannam@135 173 }
cannam@135 174
cannam@135 175 inline Locked& operator=(Locked&& other) {
cannam@135 176 if (mutex != nullptr) mutex->unlock(isConst<T>() ? _::Mutex::SHARED : _::Mutex::EXCLUSIVE);
cannam@135 177 mutex = other.mutex;
cannam@135 178 ptr = other.ptr;
cannam@135 179 other.mutex = nullptr;
cannam@135 180 other.ptr = nullptr;
cannam@135 181 return *this;
cannam@135 182 }
cannam@135 183
cannam@135 184 inline void release() {
cannam@135 185 if (mutex != nullptr) mutex->unlock(isConst<T>() ? _::Mutex::SHARED : _::Mutex::EXCLUSIVE);
cannam@135 186 mutex = nullptr;
cannam@135 187 ptr = nullptr;
cannam@135 188 }
cannam@135 189
cannam@135 190 inline T* operator->() { return ptr; }
cannam@135 191 inline const T* operator->() const { return ptr; }
cannam@135 192 inline T& operator*() { return *ptr; }
cannam@135 193 inline const T& operator*() const { return *ptr; }
cannam@135 194 inline T* get() { return ptr; }
cannam@135 195 inline const T* get() const { return ptr; }
cannam@135 196 inline operator T*() { return ptr; }
cannam@135 197 inline operator const T*() const { return ptr; }
cannam@135 198
cannam@135 199 private:
cannam@135 200 _::Mutex* mutex;
cannam@135 201 T* ptr;
cannam@135 202
cannam@135 203 inline Locked(_::Mutex& mutex, T& value): mutex(&mutex), ptr(&value) {}
cannam@135 204
cannam@135 205 template <typename U>
cannam@135 206 friend class MutexGuarded;
cannam@135 207 };
cannam@135 208
cannam@135 209 template <typename T>
cannam@135 210 class MutexGuarded {
cannam@135 211 // An object of type T, guarded by a mutex. In order to access the object, you must lock it.
cannam@135 212 //
cannam@135 213 // Write locks are not "recursive" -- trying to lock again in a thread that already holds a lock
cannam@135 214 // will deadlock. Recursive write locks are usually a sign of bad design.
cannam@135 215 //
cannam@135 216 // Unfortunately, **READ LOCKS ARE NOT RECURSIVE** either. Common sense says they should be.
cannam@135 217 // But on many operating systems (BSD, OSX), recursively read-locking a pthread_rwlock is
cannam@135 218 // actually unsafe. The problem is that writers are "prioritized" over readers, so a read lock
cannam@135 219 // request will block if any write lock requests are outstanding. So, if thread A takes a read
cannam@135 220 // lock, thread B requests a write lock (and starts waiting), and then thread A tries to take
cannam@135 221 // another read lock recursively, the result is deadlock.
cannam@135 222
cannam@135 223 public:
cannam@135 224 template <typename... Params>
cannam@135 225 explicit MutexGuarded(Params&&... params);
cannam@135 226 // Initialize the mutex-guarded object by passing the given parameters to its constructor.
cannam@135 227
cannam@135 228 Locked<T> lockExclusive() const;
cannam@135 229 // Exclusively locks the object and returns it. The returned `Locked<T>` can be passed by
cannam@135 230 // move, similar to `Own<T>`.
cannam@135 231 //
cannam@135 232 // This method is declared `const` in accordance with KJ style rules which say that constness
cannam@135 233 // should be used to indicate thread-safety. It is safe to share a const pointer between threads,
cannam@135 234 // but it is not safe to share a mutable pointer. Since the whole point of MutexGuarded is to
cannam@135 235 // be shared between threads, its methods should be const, even though locking it produces a
cannam@135 236 // non-const pointer to the contained object.
cannam@135 237
cannam@135 238 Locked<const T> lockShared() const;
cannam@135 239 // Lock the value for shared access. Multiple shared locks can be taken concurrently, but cannot
cannam@135 240 // be held at the same time as a non-shared lock.
cannam@135 241
cannam@135 242 inline const T& getWithoutLock() const { return value; }
cannam@135 243 inline T& getWithoutLock() { return value; }
cannam@135 244 // Escape hatch for cases where some external factor guarantees that it's safe to get the
cannam@135 245 // value. You should treat these like const_cast -- be highly suspicious of any use.
cannam@135 246
cannam@135 247 inline const T& getAlreadyLockedShared() const;
cannam@135 248 inline T& getAlreadyLockedShared();
cannam@135 249 inline T& getAlreadyLockedExclusive() const;
cannam@135 250 // Like `getWithoutLock()`, but asserts that the lock is already held by the calling thread.
cannam@135 251
cannam@135 252 private:
cannam@135 253 mutable _::Mutex mutex;
cannam@135 254 mutable T value;
cannam@135 255 };
cannam@135 256
cannam@135 257 template <typename T>
cannam@135 258 class MutexGuarded<const T> {
cannam@135 259 // MutexGuarded cannot guard a const type. This would be pointless anyway, and would complicate
cannam@135 260 // the implementation of Locked<T>, which uses constness to decide what kind of lock it holds.
cannam@135 261 static_assert(sizeof(T) < 0, "MutexGuarded's type cannot be const.");
cannam@135 262 };
cannam@135 263
cannam@135 264 template <typename T>
cannam@135 265 class Lazy {
cannam@135 266 // A lazily-initialized value.
cannam@135 267
cannam@135 268 public:
cannam@135 269 template <typename Func>
cannam@135 270 T& get(Func&& init);
cannam@135 271 template <typename Func>
cannam@135 272 const T& get(Func&& init) const;
cannam@135 273 // The first thread to call get() will invoke the given init function to construct the value.
cannam@135 274 // Other threads will block until construction completes, then return the same value.
cannam@135 275 //
cannam@135 276 // `init` is a functor(typically a lambda) which takes `SpaceFor<T>&` as its parameter and returns
cannam@135 277 // `Own<T>`. If `init` throws an exception, the exception is propagated out of that thread's
cannam@135 278 // call to `get()`, and subsequent calls behave as if `get()` hadn't been called at all yet --
cannam@135 279 // in other words, subsequent calls retry initialization until it succeeds.
cannam@135 280
cannam@135 281 private:
cannam@135 282 mutable _::Once once;
cannam@135 283 mutable SpaceFor<T> space;
cannam@135 284 mutable Own<T> value;
cannam@135 285
cannam@135 286 template <typename Func>
cannam@135 287 class InitImpl;
cannam@135 288 };
cannam@135 289
cannam@135 290 // =======================================================================================
cannam@135 291 // Inline implementation details
cannam@135 292
cannam@135 293 template <typename T>
cannam@135 294 template <typename... Params>
cannam@135 295 inline MutexGuarded<T>::MutexGuarded(Params&&... params)
cannam@135 296 : value(kj::fwd<Params>(params)...) {}
cannam@135 297
cannam@135 298 template <typename T>
cannam@135 299 inline Locked<T> MutexGuarded<T>::lockExclusive() const {
cannam@135 300 mutex.lock(_::Mutex::EXCLUSIVE);
cannam@135 301 return Locked<T>(mutex, value);
cannam@135 302 }
cannam@135 303
cannam@135 304 template <typename T>
cannam@135 305 inline Locked<const T> MutexGuarded<T>::lockShared() const {
cannam@135 306 mutex.lock(_::Mutex::SHARED);
cannam@135 307 return Locked<const T>(mutex, value);
cannam@135 308 }
cannam@135 309
cannam@135 310 template <typename T>
cannam@135 311 inline const T& MutexGuarded<T>::getAlreadyLockedShared() const {
cannam@135 312 #ifdef KJ_DEBUG
cannam@135 313 mutex.assertLockedByCaller(_::Mutex::SHARED);
cannam@135 314 #endif
cannam@135 315 return value;
cannam@135 316 }
cannam@135 317 template <typename T>
cannam@135 318 inline T& MutexGuarded<T>::getAlreadyLockedShared() {
cannam@135 319 #ifdef KJ_DEBUG
cannam@135 320 mutex.assertLockedByCaller(_::Mutex::SHARED);
cannam@135 321 #endif
cannam@135 322 return value;
cannam@135 323 }
cannam@135 324 template <typename T>
cannam@135 325 inline T& MutexGuarded<T>::getAlreadyLockedExclusive() const {
cannam@135 326 #ifdef KJ_DEBUG
cannam@135 327 mutex.assertLockedByCaller(_::Mutex::EXCLUSIVE);
cannam@135 328 #endif
cannam@135 329 return const_cast<T&>(value);
cannam@135 330 }
cannam@135 331
cannam@135 332 template <typename T>
cannam@135 333 template <typename Func>
cannam@135 334 class Lazy<T>::InitImpl: public _::Once::Initializer {
cannam@135 335 public:
cannam@135 336 inline InitImpl(const Lazy<T>& lazy, Func&& func): lazy(lazy), func(kj::fwd<Func>(func)) {}
cannam@135 337
cannam@135 338 void run() override {
cannam@135 339 lazy.value = func(lazy.space);
cannam@135 340 }
cannam@135 341
cannam@135 342 private:
cannam@135 343 const Lazy<T>& lazy;
cannam@135 344 Func func;
cannam@135 345 };
cannam@135 346
cannam@135 347 template <typename T>
cannam@135 348 template <typename Func>
cannam@135 349 inline T& Lazy<T>::get(Func&& init) {
cannam@135 350 if (!once.isInitialized()) {
cannam@135 351 InitImpl<Func> initImpl(*this, kj::fwd<Func>(init));
cannam@135 352 once.runOnce(initImpl);
cannam@135 353 }
cannam@135 354 return *value;
cannam@135 355 }
cannam@135 356
cannam@135 357 template <typename T>
cannam@135 358 template <typename Func>
cannam@135 359 inline const T& Lazy<T>::get(Func&& init) const {
cannam@135 360 if (!once.isInitialized()) {
cannam@135 361 InitImpl<Func> initImpl(*this, kj::fwd<Func>(init));
cannam@135 362 once.runOnce(initImpl);
cannam@135 363 }
cannam@135 364 return *value;
cannam@135 365 }
cannam@135 366
cannam@135 367 } // namespace kj
cannam@135 368
cannam@135 369 #endif // KJ_MUTEX_H_