简易array内存池实现

应用场景:一个程序执行过程中,需要动态分配非常多的某struct,以构成链表或其它什么的。若每次都malloc,会极大地影响效率,可以预先分配一大片空间池,构成struct[]数组,要用时,从里面取一个。当该池全部用完时,自动分配下一个池。

这个方法比较通用,缺点是不具备回收功能。要想实现回收,可以在每个array元素中,添加next、prev,构成使用list、未使用list,可以参考nginx中ngx_connection_t的实现。

typedef struct array_pool_s array_pool_t;

struct array_pool_s {
	array_pool_t *next;
	array_pool_t *current;
	int size;
	int n;
	int used;
	void *elt;
};

array_pool_t *array_init(int size,int n)
{
	array_pool_t *pool;

	pool = malloc(sizeof(array_pool_t));
	pool->size = size;
	pool->n = n;
	pool->used = 0;
	pool->elt = malloc(size*n);
	memset(pool->elt,'\0',size*n);
	pool->next = NULL;

	return pool;
}

void * array_get_item(array_pool_t *pool)
{
	array_pool_t *current;

	current = pool->current;
	if(current->used >= current->n) {
		current->next = array_init(pool->size,pool->n);
		current = current->next;
		pool->current = current;
	}
	current->used++;
	return (void*)((void*)current->elt + (current->used-1)*pool->size);
}

void array_free(array_pool_t *pool)
{
	array_pool_t *tmp;
	while(pool)
	{
		free(pool->elt);
		tmp = pool;
		pool = tmp->next;
		free(tmp);
	}
}

使用起来也很方便:

int main()
{
        array_pool_t *node_pool=NULL;
        node_pool = array_init(sizeof(node_t),75);
	node_pool->current = node_pool;

        while(1) {
               item = (node_t *)array_get_item(node_pool);
        }
        array_free(node_pool);
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值