annotate win64-msvc/include/kj/mutex.h @ 169:223a55898ab9 tip default

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