应用场景:一个程序执行过程中,需要动态分配非常多的某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);
}