annotate osx/include/kj/mutex.h @ 49:3ab5a40c4e3b

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