| 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_LOCKEDHEAP_H |
| 19 | #define HL_LOCKEDHEAP_H |
| 20 | |
| 21 | #include <mutex> |
| 22 | #include <cstddef> |
| 23 | |
| 24 | namespace HL { |
| 25 | |
| 26 | template <class LockType, class Super> |
| 27 | class LockedHeap : public Super { |
| 28 | public: |
| 29 | |
| 30 | enum { Alignment = Super::Alignment }; |
| 31 | |
| 32 | inline void * malloc (size_t sz) { |
| 33 | std::lock_guard<LockType> l (thelock); |
| 34 | return Super::malloc (sz); |
| 35 | } |
| 36 | |
| 37 | inline auto free (void * ptr) { |
| 38 | std::lock_guard<LockType> l (thelock); |
| 39 | return Super::free (ptr); |
| 40 | } |
| 41 | |
| 42 | inline auto free (void * ptr, size_t sz) { |
| 43 | std::lock_guard<LockType> l (thelock); |
| 44 | return Super::free (ptr, sz); |
| 45 | } |
| 46 | |
| 47 | inline void * memalign (size_t alignment, size_t sz) { |
| 48 | std::lock_guard<LockType> l (thelock); |
| 49 | return Super::memalign (alignment, sz); |
| 50 | } |
| 51 | |
| 52 | inline size_t getSize (void * ptr) const { |
| 53 | std::lock_guard<LockType> l (thelock); |
| 54 | return Super::getSize (ptr); |
| 55 | } |
| 56 | |
| 57 | inline size_t getSize (void * ptr) { |
| 58 | std::lock_guard<LockType> l (thelock); |
| 59 | return Super::getSize (ptr); |
| 60 | } |
| 61 | |
| 62 | inline void lock() { |
| 63 | thelock.lock(); |
| 64 | } |
| 65 | |
| 66 | inline void unlock() { |
| 67 | thelock.unlock(); |
| 68 | } |
| 69 | |
| 70 | private: |
| 71 | // char dummy[128]; // an effort to avoid false sharing. |
| 72 | LockType thelock; |
| 73 | }; |
| 74 | |
| 75 | } |
| 76 | |
| 77 | #endif |