#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
最新资源
- IBM FileNet Content Manager智能内容服务介绍V3.8
- C++程序设计-参考答案
- STM32超声波测距模块HC-SR04用定时器输入捕获实现测距
- 管理系统开发指南:功能要求、技术栈及安全控制
- 小学生信息管理系统,仅供参考
- IBM决策管理平台ODM介绍
- 汽车租赁管理系统,仅供参考
- 改进多任务transformer模型,以提高输血分类预测和注射种类容量回归预测的精度-医疗AI领域的多任务Transformer模型改进与应用:提高输血分类与注射容量预测的准确性
- 基于霍夫变换的人数检测软件
- IBM Process Mining流程挖掘
- 宿舍管理系统项目源代码全套技术资料.zip
- 最新仿720云全景制作源码-krpano仿720云全景网站源码 新增微信支付+打赏+场景红包
- 02326操作系统历年真题及答案2004-2023及课件PPT
- 音频采样与转换软件界面
- 租房网站项目源代码全套技术资料.zip
- java毕设项目之ssm班主任助理系统的设计与实现+jsp(完整前后端+说明文档+mysql+lw).zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈