快速业务通道

内存池的C++实现(可能还有小bug)

作者 佚名技术 来源 程序设计 浏览 发布时间 2012-06-29
 //pmb_block没走到最后 并且当前block没有可分配结点
    {
        pmb_block=pmb_block->m_pNext;//往后走吧。
    }
    if(pmb_block) //如果找到可分配结点的block
    {
        char* pfree=pmb_block->m_data+(pmb_block- >m_nFirst*m_nUnitSize);
        pmb_block->m_nFirst=*((USHORT*)pfree);
        pmb_block->m_nFree--;//可分配节点自减
        return (void*)pfree;
    }
    else//如果找不到,此时pmb_block值为0
    {
        if(m_nGrowSize==NULL)
            return NULL;
        pmb_block=new (m_nGrowSize,m_nUnitSize)MemoryBlock (m_nGrowSize,m_nUnitSize);
        if(!pmb_block) //new不成功
            return NULL;
        pmb_block->m_pNext=m_pFirst;//把新建的block放到最前吧
        m_pFirst=pmb_block;
        return (void*)pmb_block->m_data;
    }
}

void MemoryPool::Free(void* pfree)
{
    if(m_pFirst==NULL)
        return;
    MemoryBlock* pmb_block=m_pFirst;
    MemoryBlock* pmb_preblock=m_pFirst;
    while((ULONG)pfree<(ULONG)pmb_block->m_data||
        (ULONG)pfree>(ULONG)(pmb_block->m_data+pmb_block- >m_nSize)) //pfree不在当前block中
    {
        pmb_preblock=pmb_block;//前一个block块
        pmb_block=pmb_block->m_pNext;
        if(!pmb_block)
            return;
    }
    pmb_block->m_nFree++;//可分配数目+1
    *((USHORT*)pfree)=pmb_block->m_nFirst;
    pmb_block->m_nFirst=(USHORT)((ULONG)pfree-(ULONG)pmb_block- >m_data)/m_nUnitSize;
    if(pmb_block->m_nFree*m_nUnitSize==pmb_block->m_nSize) //如何该链块 为空
    {
        pmb_preblock->m_pNext=pmb_block->m_pNext;
        if((ULONG)pmb_preblock==(ULONG)m_pFirst)
            m_pFirst=NULL;
        delete pmb_block;
    }
}

MemoryPool::~MemoryPool(void)
{
    if(m_pFirst)
        FreeMemoryBlock(m_pFirst);
}


void MemoryPool::FreeMemoryBlock(MemoryBlock *pblock)
{
    if(pblock->m_pNext)
        FreeMemoryBlock(pblock->m_pNext);
    delete pblock;
    pblock=NULL;
}

Test.cpp

#include "MemoryPool.h"
#include "time.h"

void performance_old()
{
?????? clock_t start,stop;
?????? start = clock();//?aê?ê±??
?????? int i,b=0;
?????? for(i=0;i<=100000;i++)
?????? {
?????????? int* p=new int;
?????? }

?????? cout<<"Without MemoryPool:"<< (double) (clock()-start)<<"ms"<<endl;//ê?3?
}

void memory()
{
?????? clock_t start;
?????? start = clock();//?aê?ê±??
?????? MemoryPool mp(sizeof(int),10000,500);
?????? int i=0;
?????? for(i=0;i<=100000;i++)
?????? {
?????????? int* p=(int*)mp.Alloc();
?????? }

?????? cout<<"Using MemoryPool:"<<(double)(clock()-start) <<"ms";//ê?3?
}
int main()
{
?????? performance_old();
?????? memory();//?ú′?3?
?????? system("pa

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号