构建自己的内存池(二)

内存池的实现:

1:内存池的初始化:对每个子池进行初始化流程,将子池的入口放入内存池中,初始化block状态。

void initPools()
{
    initPool(POOL1,(void*)pool1,POOL1_BLOCK_NUM,POOL1_BLOCK_SIZE);
    initPool(POOL2,(void*)pool2,POOL2_BLOCK_NUM,POOL2_BLOCK_SIZE);
    initPool(POOL3,(void*)pool3,POOL3_BLOCK_NUM,POOL1_BLOCK_SIZE);
    return;
}

void initPool(unsigned char poolId,void *pool,unsigned short blockNum,unsigned short blockSize)
{
    BLOCK_M_T *pBmt = NULL;
    BLOCK_M_T *pPreBmt = NULL;

    g_memoryPools[poolId].blockSzie = blockSize;
    g_memoryPools[poolId].blockUsed = 0;
    g_memoryPools[poolId].pFirstBlock = (BLOCK_M_T*)pool;

    pBmt = (BLOCK_M_T*)pool;
    for(int i=0;i<blockNum;i++)
    {
        pBmt->payload = 0;
        pBmt->state = BLOCK_UNUSED|poolId;
        pBmt->pNext = (BLOCK_M_T*)((unsigned char*)(pBmt+1)+blockSize);
        pPreBmt = pBmt;
        pBmt = pBmt->pNext;
    }

    pPreBmt->pNext = NULL;
    return;
}

 2:内存空间的分配:从指定的子池中获取空闲的block,子池中包含所有的未被分陪的block,每分配一个block后,子池中将不在包含该block。

void* getPoolBlock(unsigned char poolId,unsigned short size)
{
    BLOCK_M_T *pBmt = NULL;

    pBmt = (BLOCK_M_T*)g_memoryPools[poolId].pFirstBlock;

    if(!pBmt)
    {
        return NULL;
    }

    g_memoryPools[poolId].pFirstBlock = pBmt->pNext;
    pBmt->state = BLOCK_USED|poolId;
    pBmt->payload = size;
    pBmt->pNext = NULL;

    return (pBmt+1);
}

3:内存空间的释放:根据实际分配空间的地址可以定位到相应的block管理头,根据block管理头中的状态信息可以确定对应的子池,修改block状态然后将该block挂接到对应子池的头上。供下次分配。

void memPools_free(void* pBlock)
{
    BLOCK_M_T *pBmt = NULL;
    unsigned short poolId = -1;
 
    pBmt = (BLOCK_M_T*)pBlock;

    pBmt--;
    poolId = pBmt->state & 0x3F;

    pBmt->payload = 0;
    pBmt->state = BLOCK_UNUSED|poolId;
    pBmt->pNext = g_memoryPools[poolId].pFirstBlock;
    g_memoryPools[poolId].pFirstBlock = pBmt;

    return;
}

 

这只是一个简单内存池实现,实际的应用中可能还要考虑到效率并加上相关的调试的功能。但其包含了内存池管理的基本思想。

转载请注明原始出处:http://www.cnblogs.com/chencheng/archive/2012/06/22/2558783.html

posted @ 2012-06-23 15:12  平凡之路  阅读(2361)  评论(0编辑  收藏  举报