2009年9月21日 星期一

Memory Pool

第一次寫類似的玩意,紀念一下。
原理很簡單,就是用過的Memory不立刻釋放,下一次如果有人使用,就不必再向作業系統索取記憶體。
這裡的作法簡化了很多東西,不保證Thread-Safe。

Header File

#ifndef _MemPool_H_
#define _MemPool_H_

#ifdef __cplusplus
extern "C"
{
#endif

typedef struct memblock
{
void *data;
struct memblock *next;
struct memblock *createnext;
} memblock_t;

typedef struct mempool
{
int datasize;
memblock_t *free_linkhead;
memblock_t *create_linkhead;
} mempool_t;

mempool_t *mempool_init(int initial, int datasize);
void mempool_dealloc(mempool_t *);
memblock_t *mempool_get(mempool_t *);
void mempool_release(mempool_t *, memblock_t *);

#ifdef __cplusplus
}
#endif

#endif


Implementation



#include <stdlib.h>
#include "mempool.h"

static memblock_t* mempool_create(mempool_t *pool)
{
memblock_t *block = malloc(sizeof(memblock_t));
block->data = malloc(pool->datasize);
block->next = NULL;
block->createnext = pool->create_linkhead;
pool->create_linkhead = block;
return block;
}

mempool_t *mempool_init(int initial, int datasize)
{
int i;
mempool_t *pool =malloc(sizeof(mempool_t));
pool->datasize = datasize;
pool->free_linkhead = pool->create_linkhead = NULL;
for (i = 0; i < initial; i++) {
memblock_t *block = mempool_create(pool);
mempool_release(pool, block);
}
return pool;
}

void mempool_dealloc(mempool_t *pool)
{
memblock_t *block = pool->create_linkhead;
while (pool->create_linkhead)
{
block = pool->create_linkhead;
pool->create_linkhead = block->createnext;
free(block->data);
free(block);
}
free(pool);
}

memblock_t *mempool_get(mempool_t * pool)
{
memblock_t *block = NULL;
if (pool->free_linkhead)
{
block = pool->free_linkhead;
pool->free_linkhead = pool->free_linkhead->next;
block->next = NULL;
}
else
{
block = mempool_create(pool);
}
return block;
}

void mempool_release(mempool_t *pool, memblock_t *block)
{
block->next = pool->free_linkhead;
pool->free_linkhead = block;
}


至於Memory Pool的原理可以參考 維基上面的解釋

沒有留言:

張貼留言

 

我們搬家了

新部落格在http://b-plurkers.com/