#include"MemoryPool.h"
MemoryPool::MemoryBlock::MemoryBlock(USHORT nTypes , USHORT nUnitSize )
{
this->nSize=nTypes*nUnitSize;
nFree=nTypes;
nFirst=0;
pNext=NULL;
{
char * pData = aData;
for (USHORT i = 1; i < nTypes; i++)
{
*reinterpret_cast<USHORT*>(pData) = i;
pData += nUnitSize;
}
}
}
MemoryPool::MemoryPool(USHORT unitSize,USHORT initSize,USHORT growSize)
{
this->initSize=initSize;
this->growSize=growSize;
if(unitSize<=2)
{
this->unitSize=2;
}
else if(unitSize>4)
{
this->unitSize = (unitSize + (MEMORY_ALLGNMENT-1)) & ~(MEMORY_ALLGNMENT-1);
}
else
{
this->unitSize=4;
}
pBlock=NULL;
blockNum=0;
}
void* MemoryPool::alloc()
{
if(!pBlock)
{
pBlock=new(initSize,unitSize)MemoryBlock(initSize,unitSize);
blockNum++;
}
MemoryBlock* pMyBlock = pBlock;
while (pMyBlock && !pMyBlock->nFree )
{
pMyBlock = pMyBlock->pNext;//寻找空闲内存块
}
if(pMyBlock)
{
char* pFree=(pMyBlock->aData+pMyBlock->nFirst*unitSize);//返回空闲地址
pMyBlock->nFree--;
pMyBlock->nFirst=*((USHORT*)pFree);
return static_cast<void*>(pFree);
}
else
{
if ( !growSize )
return NULL;
pMyBlock = new(growSize,unitSize)MemoryBlock(growSize,unitSize);;//扩展新的内存块
blockNum++;
pMyBlock->pNext = pBlock;
pBlock = pMyBlock;
pMyBlock->nFree--;
pMyBlock->nFirst=1;
return static_cast<void*>(pMyBlock->aData);
}
}
void MemoryPool::free(void* pFree)
{
MemoryBlock* pMyBlock = pBlock;
while ( ((ULONG)pMyBlock->aData > (ULONG)pFree) ||
((ULONG)pFree >= ((ULONG)pMyBlock->aData + pMyBlock->nSize)) )//判断内存地址是否在内存池内
{
pMyBlock=pMyBlock->pNext;
}
if(!pMyBlock)
return;
pMyBlock->nFree++;
*((USHORT*)pFree) = pMyBlock->nFirst;
pMyBlock->nFirst = (USHORT)(((ULONG)pFree-(ULONG)(pBlock->aData)) / unitSize);//修改链表结构
if(pMyBlock->nFree*unitSize==pMyBlock->nSize)//内存块完全空闲
{
if(pBlock==pMyBlock)
{
pBlock=pMyBlock->pNext;
MemoryBlock::operator delete(pMyBlock,0);//空闲块在头部
blockNum--;
}
else //空闲块在链表中部
{
MemoryBlock* pTemp=pBlock;
while(pTemp->pNext!=pMyBlock)
{
pTemp=pTemp->pNext;
}
pTemp->pNext=pMyBlock->pNext;
MemoryBlock::operator delete(pMyBlock,0);
blockNum--;
}
}
}
MemoryPool::~MemoryPool()
{
MemoryBlock* pMyBlock=pBlock;
while(pBlock)
{
pMyBlock=pBlock;
pBlock=pMyBlock->pNext;
MemoryBlock::operator delete(pMyBlock,0);
}
}
Emiyasstar__
- 粉丝: 476
- 资源: 20
最新资源
- 构建数据库故障监控策略:技术实现与代码实践
- 【windows实用工具】+【统计文件夹内所有文件(包含文件夹)大小】+【方便我们管理文件 】
- AI+Go 打造你的智能办公助手
- 使用SDSOC和Xilinx Ultrascale+ZCU102平台在嵌入式操作系统中部署 CNN 加速器+项目源码+文档说明
- 个人汽车销售工作计划.docx
- 服装销售店长工作计划范文.docx
- 70154兔兔答题源码一款前后端开源的移动端答题系统
- 电视节目项目策划书.docx
- 微商防伪防窜货溯源查询系统源码二维码查询导入导出/扫码发货/物流查询
- 《测绘程序设计》第49章 利用五点光滑法进行曲线拟合案例,C# winform
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈