annotate win64-msvc/include/kj/mutex.h @ 64:eccd51b72864

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