dl
dl_memory_pool.h
浏览该文件的文档.
1
15#pragma once
16
17#include <list>
18#include <cassert>
19#include <functional>
20#include <cstdlib>
21
22#include "io/dl_log.h"
23#include "math/dl_math.h"
24
25#ifdef NDEBUG
26constexpr bool OUTPUT_DEBUG = false;
27constexpr bool OUTPUT_ADD = false;
28constexpr bool OUTPUT_MOVE = false;
29constexpr bool OUTPUT_STACK = false;
30#else
31constexpr bool OUTPUT_DEBUG = true;
32constexpr bool OUTPUT_ADD = true;
33constexpr bool OUTPUT_MOVE = false;
34constexpr bool OUTPUT_STACK = false;
35#endif
36
37namespace dl
38{
39
41{
42 uint32_t _count;
43};
44
45
47template<typename T>
48class GC
49{
50 template<typename TT>
51 friend class PoolList;
52public:
53 GC() :_p(nullptr), _ref(nullptr) {}
54 GC(const GC<T>& b) : _p(b._p), _ref(b._ref) { if (_ref)++_ref->_count; }
55 operator bool()
56 {
57 return _p != nullptr;
58 }
59
61 {
62 return _p;
63 }
64
66 {
67 return *_p;
68 }
69
71 {
72 //如果相同,则什么都不做
73 if (_p == b._p)
74 {
75 return *this;
76 }
77
78 //不同,且有原对象,减少1次对原对象的引用
79 if (_p)
80 {
81 assert(_ref && _ref->_count > 0);
82 --_ref->_count;
83 _check_dtor();
84 }
85
86 //复制,再增加b的一次引用(b可能为空)
87 _p = b._p;
88 _ref = b._ref;
89 if (_ref)
90 ++_ref->_count;
91
92 return *this;
93 }
94
96 void CancelRef()
97 {
98 if (_p)
99 {
100 assert(_ref && _ref->_count > 0);
101 --_ref->_count;
102 _check_dtor();
103 }
104 }
105
106 size_t GetRefCount()
107 {
108 if (_p)
109 {
110 assert(_ref && _ref->_count > 0);
111 return _ref->_count;
112 }
113 return 0;
114 }
115
118 {
119 return _p;
120 }
121
123 {
124 // 如果退出时崩溃到这里,说明有GC<T>后于PoolList析构,需要使其退出主函数之前析构
125 // 简单说就是 不要使用gc全局变量,因为可能晚于GC系统析构
126
127 // Text包含Sprite,如果Sprite先全局析构,再全局析构Text也会出问题
128 // 此问题已解决,先使用一下gcSprite,PoolList<Sprite>就会先于PoolList<Text>析构
129 if (_p)
130 {
131 assert(_ref && _ref->_count > 0);
132 --_ref->_count;
133 _check_dtor();
134 }
135 }
136
137private:
138 GcRefInfo* _ref;
139 T* _p;
140
141 void _check_dtor()
142 {
143 if (_ref->_count == 0)
144 {//显式析构
145 _p->~T();
146 _p = nullptr;
147 _ref = nullptr;
148 }
149 }
150};
151
152template<typename T>
153class PoolList
154{
155 friend class MemoryPool;
156public:
158 void SetCallbackDelete(std::function<void()> func)
159 {
160 _cbDelete = func;
161 }
162 constexpr unsigned GetNodeSize()
163 {
164 return sizeof(T) + sizeof(GcRefInfo);
165 }
166private:
167 PoolList() {}
168 // 取一个位置
169 template<typename... Args>
170 GC<T> GetGC(Args&& ...args)
171 {
172 void* p = nullptr;
173 // 如果没有就新建内存
174 if (_listFree.empty())
175 _add_free();
176
177 //
178 if (_listFree.empty())
179 {
180 log("PoolArray::GetGC: 失败!");
181 return GC<T>();
182 }
183
184 p = _listFree.front();
185 _listFree.pop_front();
186 _listUsed.push_back(p);
187
188 GC<T> ret;
189 ret._p = new (p) T(args...);
190 ret._ref = new ((unsigned char*)p + sizeof(T)) GcRefInfo;
191 ret._ref->_count = 1;
192
193 return ret;
194 }
195
196
197 ~PoolList()
198 {
199 // 不能使用全局的GC变量
200
201 // Used列表的内存强行回收
202 for (auto& iter : _listUsed)
203 free(iter);// _aligned_free(iter);
204
205 for (auto& iter : _listFree)
206 free(iter);// _aligned_free(iter);
207
208 if (OUTPUT_DEBUG)
209 {
210 log_easy(fmt::format("释放 {}({}byte)内存,(已使用{}+空闲{})个\n",
211 typeid(T).name(), GetNodeSize(), _listUsed.size(), _listFree.size()));
212 }
213
214 if(_cbDelete)
215 _cbDelete();
216 }
217private:
218 // 可使用的节点内存
219 std::list<void*> _listFree; // TODO 可改为vector
220 std::list<void*> _listUsed;
221 // 回调
222 std::function<void()> _cbDelete;
223
224 // 批量new
225 void _add_free()
226 {
227 //先检查used转移到free
228 size_t count = 0;
229 if (_listUsed.size() > 10000)//100m (sizeof(GcRefInfo) + sizeof(T)) > 1024 * 1024 * 100
230 {
231 for (auto iter = _listUsed.begin(); iter != _listUsed.end();)
232 {
233 void* p = (unsigned char*)*iter + sizeof(T);
234 if (((GcRefInfo*)p)->_count == 0)
235 {
236 _listFree.push_back(*iter);
237 _listUsed.erase(iter++);
238 ++count;
239 }
240 else
241 ++iter;
242 }
244 {
245 LogStackTrack l{ OUTPUT_STACK };
246 log_test("转移 {}({}byte)内存,({})个",
247 typeid(T).name(), GetNodeSize(), count);
248 }
249 }
250
251
252 //转移过少
253 if (count <= _listUsed.size() / 2)
254 {
255 //
256 size_t num = _listUsed.size() + 10;
257 for (size_t i = 0; i != num; ++i)
258 {
259 unsigned MEM_SIZE = GetNodeSize();// Math::CeilToPow2(GetNodeSize());
260 void* p = malloc(MEM_SIZE);// _aligned_malloc(MEM_SIZE, 16);
261
262 if (p == nullptr)
263 {
264 log("malloc失败!");
265 return;
266 }
267 _listFree.push_back(p);
268 }
270 {
271 LogStackTrack l{ OUTPUT_STACK };
272 log_test("分配 {}({}byte)内存,({})个",
273 typeid(T).name(), GetNodeSize(), _listFree.size());
274 }
275 }
276
277 }
278};
279
280
281
283class MemoryPool
284{
285public:
290 template<typename T, typename... Args>
291 static GC<T> GetGC(Args&& ...args)
292 {
293 return GetPoolList<T>().GetGC(args...);
294 }
295
296 template<typename T>
298 {
299 static PoolList<T> pool_list;
300 return pool_list;
301 }
302private:
303 MemoryPool() = delete;
304};
305
311template<typename T, typename... Args>
312auto get_gc(Args&& ...args)
313{
314 return MemoryPool::GetGC<T>(args...);
315}
316
317
318}
引用计数对象,通过get_gc函数创建
T * GetPointer()
直接获取指针,注意生命周期
size_t GetRefCount()
GC< T > & operator=(const GC< T > &b)
GC(const GC< T > &b)
void CancelRef()
取消引用对象
static GC< T > GetGC(Args &&...args)
定义一个GC变量(引用计数内存池)
static PoolList< T > & GetPoolList()
内存池数据
constexpr unsigned GetNodeSize()
friend class MemoryPool
void SetCallbackDelete(std::function< void()> func)
设置删除回调
日志系统
#define log_test(...)
数学相关的通用算法
constexpr bool OUTPUT_ADD
constexpr bool OUTPUT_STACK
constexpr bool OUTPUT_MOVE
constexpr bool OUTPUT_DEBUG
auto get_gc(Args &&...args)
定义一个GC变量(引用计数内存池)
void log_easy(std::string_view str)
输出日志
void log(std::string_view str, const std::source_location location=std::source_location::current())
以当前设置输出