annotate osx/include/kj/mutex.h @ 83:ae30d91d2ffe

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