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