| 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 | #ifndef HL_RECURSIVELOCK_H |
| 19 | #define HL_RECURSIVELOCK_H |
| 20 | |
| 21 | #include <cassert> |
| 22 | #include "threads/cpuinfo.h" |
| 23 | |
| 24 | /** |
| 25 | * @class RecursiveLockType |
| 26 | * @brief Implements a recursive lock using some base lock representation. |
| 27 | * @param BaseLock The base lock representation. |
| 28 | */ |
| 29 | |
| 30 | namespace HL { |
| 31 | |
| 32 | template <class BaseLock> |
| 33 | class RecursiveLockType : public BaseLock { |
| 34 | public: |
| 35 | |
| 36 | inline RecursiveLockType (void) |
| 37 | : _tid (-1), |
| 38 | _recursiveDepth (0) |
| 39 | {} |
| 40 | |
| 41 | inline void lock() { |
| 42 | auto currthread = CPUInfo::getThreadId(); |
| 43 | if (_tid == currthread) { |
| 44 | _recursiveDepth++; |
| 45 | } else { |
| 46 | BaseLock::lock(); |
| 47 | _tid = currthread; |
| 48 | _recursiveDepth++; |
| 49 | } |
| 50 | } |
| 51 | |
| 52 | inline void unlock (void) { |
| 53 | auto currthread = (int) CPUInfo::getThreadId(); |
| 54 | if (_tid == currthread) { |
| 55 | _recursiveDepth--; |
| 56 | if (_recursiveDepth == 0) { |
| 57 | _tid = -1; |
| 58 | BaseLock::unlock(); |
| 59 | } |
| 60 | } else { |
| 61 | // We tried to unlock it but we didn't lock it! |
| 62 | // This should never happen. |
| 63 | assert (0); |
| 64 | abort(); |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | private: |
| 69 | int _tid; /// The lock owner's thread id. -1 if unlocked. |
| 70 | int _recursiveDepth; /// The recursion depth of the lock. |
| 71 | }; |
| 72 | |
| 73 | } |
| 74 | |
| 75 | |
| 76 | |
| 77 | |
| 78 | #endif |