Resource Tuner
Loading...
Searching...
No Matches
MemoryPool.h
Go to the documentation of this file.
1// Copyright (c) Qualcomm Technologies, Inc. and/or its subsidiaries.
2// SPDX-License-Identifier: BSD-3-Clause-Clear
3
4#ifndef MEMORY_POOL_H
5#define MEMORY_POOL_H
6
31#include <vector>
32#include <exception>
33#include <mutex>
34#include <memory>
35#include <unordered_map>
36#include <typeindex>
37#include <typeinfo>
38
39#include "Utils.h"
40#include "Logger.h"
41
42typedef struct _memoryNode {
43 _memoryNode* next;
44 void* block;
45} MemoryNode;
46
54private:
55 static std::shared_ptr<MemoryPool> mMemoryPoolInstance;
56 std::mutex mMemoryPoolMutex;
57
58 MemoryNode* mFreeListHead;
59 MemoryNode* mFreeListTail;
60 MemoryNode* mAllocatedListHead;
61
62 int32_t mBlockSize;
63 int32_t mfreeBlocks;
64
65 int32_t addNodesToFreeList(int32_t blockCount);
66
67public:
68 MemoryPool(int32_t blockSize);
70
78 int32_t makeAllocation(int32_t blockCount);
79
87 void* getBlock();
88
93 void freeBlock(void* block);
94};
95
96class PoolWrapper {
97private:
98 std::unordered_map<std::type_index, MemoryPool*> mMemoryPoolRefs;
99 std::mutex mPoolWrapperMutex;
100
101 MemoryPool* getMemoryPool(std::type_index typeIndex);
102
103 int32_t makeAllocation(int32_t blockCount, int32_t blockSize, std::type_index typeIndex);
104 void* getBlock(int32_t blockSize, std::type_index typeIndex);
105 void freeBlock(std::type_index typeIndex, void* block);
106
107public:
108 PoolWrapper() {}
109 ~PoolWrapper() {}
110
116 template <typename T>
117 int32_t makeAllocation(int32_t blockCount) {
118 return makeAllocation(blockCount, sizeof(T), std::type_index(typeid(T)));
119 }
120
127 template <typename T>
128 void* getBlock() {
129 return getBlock(sizeof(T), std::type_index(typeid(T)));
130 }
131
137 template<typename T>
138 typename std::enable_if<std::is_class<T>::value, void>::type
139 freeBlock(void* block) {
140 reinterpret_cast<T*>(block)->~T();
141 freeBlock(std::type_index(typeid(T)), block);
142 }
143
148 template<typename T>
149 typename std::enable_if<!std::is_class<T>::value, void>::type
150 freeBlock(void* block) {
151 freeBlock(std::type_index(typeid(T)), block);
152 }
153};
154
155std::shared_ptr<PoolWrapper> getPoolWrapper();
156
157template <typename T>
158inline void MakeAlloc(int32_t blockCount) {
159 getPoolWrapper()->makeAllocation<T>(blockCount);
160}
161
162template <typename T>
163inline void* GetBlock() {
164 return getPoolWrapper()->getBlock<T>();
165}
166
167template <typename T>
168inline void FreeBlock(void* block) {
169 getPoolWrapper()->freeBlock<T>(block);
170}
171
172#endif
173
MemoryPool.
Definition MemoryPool.h:53
void * getBlock()
Get an allocated block for the already allocated type T.
void freeBlock(void *block)
Free an allocated block of the specified type T.
int32_t makeAllocation(int32_t blockCount)
Allocate memory for the specified type T.