annotate win32-mingw/include/kj/mutex.h @ 63:0f2d93caa50c

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