Files
dl_old/dl/memory/dl_memory_pool.h
T
2026-03-01 21:54:57 +08:00

318 lines
6.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* @file dl_memory_pool.h
* @brief 基于引用计数的内存池
*
* @version 1.0
* @author lveyou
* @date 21-08-30
*
* @note 内存池修改为维护1个free列表和1个used列表
* @note 定期将used列表引用计数为0的移动回free列表
*
* @note 注意gc的类之间不要存在引用关系,不过也可以如下处理:
* @note gcText包含gcSprite,我们使PoolList<gcText>先释放即可
*/
#pragma once
#include <list>
#include <cassert>
#include <functional>
#include <cstdlib>
#include "io/dl_log.h"
#include "math/dl_math.h"
#ifdef NDEBUG
constexpr bool OUTPUT_DEBUG = false;
constexpr bool OUTPUT_ADD = false;
constexpr bool OUTPUT_MOVE = false;
constexpr bool OUTPUT_STACK = false;
#else
constexpr bool OUTPUT_DEBUG = true;
constexpr bool OUTPUT_ADD = true;
constexpr bool OUTPUT_MOVE = false;
constexpr bool OUTPUT_STACK = false;
#endif
namespace dl
{
struct GcRefInfo
{
uint32_t _count;
};
//! 引用计数对象,通过get_gc函数创建
template<typename T>
class GC
{
template<typename TT>
friend class PoolList;
public:
GC() :_p(nullptr), _ref(nullptr) {}
GC(const GC<T>& b) : _p(b._p), _ref(b._ref) { if (_ref)++_ref->_count; }
operator bool()
{
return _p != nullptr;
}
T* operator->()
{
return _p;
}
T& operator*()
{
return *_p;
}
GC<T>& operator=(const GC<T>& b)
{
//如果相同,则什么都不做
if (_p == b._p)
{
return *this;
}
//不同,且有原对象,减少1次对原对象的引用
if (_p)
{
assert(_ref && _ref->_count > 0);
--_ref->_count;
_check_dtor();
}
//复制,再增加b的一次引用(b可能为空)
_p = b._p;
_ref = b._ref;
if (_ref)
++_ref->_count;
return *this;
}
//! 取消引用对象
void CancelRef()
{
if (_p)
{
assert(_ref && _ref->_count > 0);
--_ref->_count;
_check_dtor();
}
}
size_t GetRefCount()
{
if (_p)
{
assert(_ref && _ref->_count > 0);
return _ref->_count;
}
return 0;
}
//! 直接获取指针,注意生命周期
T* GetPointer()
{
return _p;
}
~GC()
{
// 如果退出时崩溃到这里,说明有GC<T>后于PoolList析构,需要使其退出主函数之前析构
// 简单说就是 不要使用gc全局变量,因为可能晚于GC系统析构
// Text包含Sprite,如果Sprite先全局析构,再全局析构Text也会出问题
// 此问题已解决,先使用一下gcSprite,PoolList<Sprite>就会先于PoolList<Text>析构
if (_p)
{
assert(_ref && _ref->_count > 0);
--_ref->_count;
_check_dtor();
}
}
private:
GcRefInfo* _ref;
T* _p;
void _check_dtor()
{
if (_ref->_count == 0)
{//显式析构
_p->~T();
_p = nullptr;
_ref = nullptr;
}
}
};
//! 内存池数据
template<typename T>
class PoolList
{
friend class MemoryPool;
public:
//! 设置删除回调
void SetCallbackDelete(std::function<void()> func)
{
_cbDelete = func;
}
constexpr unsigned GetNodeSize()
{
return sizeof(T) + sizeof(GcRefInfo);
}
private:
PoolList() {}
// 取一个位置
template<typename... Args>
GC<T> GetGC(Args&& ...args)
{
void* p = nullptr;
// 如果没有就新建内存
if (_listFree.empty())
_add_free();
//
if (_listFree.empty())
{
log("PoolArray::GetGC: 失败!");
return GC<T>();
}
p = _listFree.front();
_listFree.pop_front();
_listUsed.push_back(p);
GC<T> ret;
ret._p = new (p) T(args...);
ret._ref = new ((unsigned char*)p + sizeof(T)) GcRefInfo;
ret._ref->_count = 1;
return ret;
}
~PoolList()
{
// 不能使用全局的GC变量
// Used列表的内存强行回收
for (auto& iter : _listUsed)
free(iter);// _aligned_free(iter);
for (auto& iter : _listFree)
free(iter);// _aligned_free(iter);
if (OUTPUT_DEBUG)
{
log_easy(fmt::format("释放 {}({}byte)内存,(已使用{}+空闲{})个\n",
typeid(T).name(), GetNodeSize(), _listUsed.size(), _listFree.size()));
}
if(_cbDelete)
_cbDelete();
}
private:
// 可使用的节点内存
std::list<void*> _listFree; // TODO 可改为vector
std::list<void*> _listUsed;
// 回调
std::function<void()> _cbDelete;
// 批量new
void _add_free()
{
//先检查used转移到free
size_t count = 0;
if (_listUsed.size() > 10000)//100m (sizeof(GcRefInfo) + sizeof(T)) > 1024 * 1024 * 100
{
for (auto iter = _listUsed.begin(); iter != _listUsed.end();)
{
void* p = (unsigned char*)*iter + sizeof(T);
if (((GcRefInfo*)p)->_count == 0)
{
_listFree.push_back(*iter);
_listUsed.erase(iter++);
++count;
}
else
++iter;
}
if (OUTPUT_DEBUG && OUTPUT_MOVE)
{
LogStackTrack l{ OUTPUT_STACK };
log_test("转移 {}({}byte)内存,({})个",
typeid(T).name(), GetNodeSize(), count);
}
}
//转移过少
if (count <= _listUsed.size() / 2)
{
//
size_t num = _listUsed.size() + 10;
for (size_t i = 0; i != num; ++i)
{
unsigned MEM_SIZE = GetNodeSize();// Math::CeilToPow2(GetNodeSize());
void* p = malloc(MEM_SIZE);// _aligned_malloc(MEM_SIZE, 16);
if (p == nullptr)
{
log("malloc失败!");
return;
}
_listFree.push_back(p);
}
if (OUTPUT_DEBUG && OUTPUT_ADD)
{
LogStackTrack l{ OUTPUT_STACK };
log_test("分配 {}({}byte)内存,({})个",
typeid(T).name(), GetNodeSize(), _listFree.size());
}
}
}
};
//! 内存池
class MemoryPool
{
public:
/**
* @brief 定义一个GC变量(引用计数内存池)
* @param[in] args 构造参数
*/
template<typename T, typename... Args>
static GC<T> GetGC(Args&& ...args)
{
return GetPoolList<T>().GetGC(args...);
}
template<typename T>
static PoolList<T>& GetPoolList()
{
static PoolList<T> pool_list;
return pool_list;
}
private:
MemoryPool() = delete;
};
/**
* @brief 定义一个GC变量(引用计数内存池)
* @param[in] T 类型名
* @param[in] args 构造参数
*/
template<typename T, typename... Args>
auto get_gc(Args&& ...args)
{
return MemoryPool::GetGC<T>(args...);
}
}