#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
最新资源
- 技术资料分享Z-Stack-API-Chinese非常好的技术资料.zip
- 技术资料分享Z-Stack 开发指南非常好的技术资料.zip
- 技术资料分享Zigbee协议栈中文说明免费非常好的技术资料.zip
- 技术资料分享Zigbee协议栈及应用实现非常好的技术资料.zip
- 技术资料分享ZigBee协议栈的研究与实现非常好的技术资料.zip
- 技术资料分享ZigBee协议栈的分析与设计非常好的技术资料.zip
- 技术资料分享Zigbee协议栈OSAL层API函数(译)非常好的技术资料.zip
- 技术资料分享zigbee无信标网络设备的加入非常好的技术资料.zip
- 技术资料分享ZigBee问答之“KVP”、“MSG”非常好的技术资料.zip
- 技术资料分享ZigBee网络管理实验例程手册非常好的技术资料.zip
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈