annotate win64-msvc/include/kj/mutex.h @ 142:75bf92aa2d1f

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