| 1 | /* -*- C++ -*- */ |
| 2 | |
| 3 | /* |
| 4 | |
| 5 | Heap Layers: An Extensible Memory Allocation Infrastructure |
| 6 | |
| 7 | Copyright (C) 2000-2020 by Emery Berger |
| 8 | http://www.emeryberger.com |
| 9 | [email protected] |
| 10 | |
| 11 | Heap Layers is distributed under the terms of the Apache 2.0 license. |
| 12 | |
| 13 | You may obtain a copy of the License at |
| 14 | http://www.apache.org/licenses/LICENSE-2.0 |
| 15 | |
| 16 | */ |
| 17 | |
| 18 | |
| 19 | #ifndef HL_MACLOCK_H |
| 20 | #define HL_MACLOCK_H |
| 21 | |
| 22 | #if defined(__APPLE__) |
| 23 | |
| 24 | /** |
| 25 | * @class MacLockType |
| 26 | * @brief Locking using OS X spin locks. |
| 27 | */ |
| 28 | |
| 29 | #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101200 |
| 30 | #define USE_UNFAIR_LOCKS 1 |
| 31 | #include <os/lock.h> |
| 32 | #else |
| 33 | #define USE_UNFAIR_LOCKS 0 |
| 34 | #include <libkern/OSAtomic.h> |
| 35 | #endif |
| 36 | |
| 37 | |
| 38 | namespace HL { |
| 39 | |
| 40 | class MacLockType { |
| 41 | public: |
| 42 | |
| 43 | MacLockType() |
| 44 | { |
| 45 | #if USE_UNFAIR_LOCKS |
| 46 | mutex = OS_UNFAIR_LOCK_INIT; |
| 47 | #else |
| 48 | mutex = OS_SPINLOCK_INIT; |
| 49 | #endif |
| 50 | } |
| 51 | |
| 52 | ~MacLockType() |
| 53 | { |
| 54 | #if USE_UNFAIR_LOCKS |
| 55 | mutex = OS_UNFAIR_LOCK_INIT; |
| 56 | #else |
| 57 | mutex = OS_SPINLOCK_INIT; |
| 58 | #endif |
| 59 | } |
| 60 | |
| 61 | inline void lock() { |
| 62 | #if USE_UNFAIR_LOCKS |
| 63 | os_unfair_lock_lock(&mutex); |
| 64 | #else |
| 65 | OSSpinLockLock (&mutex); |
| 66 | #endif |
| 67 | } |
| 68 | |
| 69 | inline void unlock() { |
| 70 | #if USE_UNFAIR_LOCKS |
| 71 | os_unfair_lock_unlock(&mutex); |
| 72 | #else |
| 73 | OSSpinLockUnlock (&mutex); |
| 74 | #endif |
| 75 | } |
| 76 | |
| 77 | private: |
| 78 | |
| 79 | #if USE_UNFAIR_LOCKS |
| 80 | os_unfair_lock mutex; |
| 81 | #else |
| 82 | OSSpinLock mutex; |
| 83 | #endif |
| 84 | |
| 85 | }; |
| 86 | |
| 87 | } |
| 88 | |
| 89 | #endif |
| 90 | |
| 91 | #endif |