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