Chinaunix首页 | 论坛 | 博客
  • 博客访问: 323035
  • 博文数量: 100
  • 博客积分: 2620
  • 博客等级: 少校
  • 技术积分: 920
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-16 02:50
文章分类

全部博文(100)

文章存档

2011年(5)

2010年(12)

2009年(83)

分类:

2010-01-14 12:53:01

Array in Nginx
 
    nginx对数组的封装,只提供了数组的内存管理的接口,没有提供数据管理的接口,即从pool中分配到内存后,就把指针交给了用户,数据的存储就由用户自己进行,没有提供一套操作数据的接口。
    nginx中数组的封装如下:
struct ngx_array_s {
 void        *elts;  /* 指向数组元素的起始地址 */
 ngx_uint_t   nelts;  /* 现使用的元素的数目 */
 size_t       size;  /* 元素的大小 */
 ngx_uint_t   nalloc; /* 分配数组中元素的数目 */
 ngx_pool_t  *pool;  /* 指向所在的内存池的指针 */
};
提供了五个接口:
(1)void ngx_array_init(ngx_array_t *array, ngx_pool_t *pool, ngx_uint_t n, size_t size)
   在指定的array对象上分配n个元素,元素大小为size。
(2)ngx_array_t *ngx_array_create(ngx_pool_t *p, ngx_uint_t n, size_t size)
   函数参数中没有array对象的指针。这个函数在内存池中创建一个array对象,并且分配n个元素,元素
大小为size。
(3)void *ngx_array_push(ngx_array_t *a)
   将array对象当作堆栈,作压栈处理。如果当前内存池没有空闲空间可用,就会申请新的内存池并且创
建一个是原来array对象两倍大小的新array,原array对象中的元素复制到新array中。比较奇怪的一点就是,分配了新的内存后(从pool),怎么没有删除老的内存地址呢?难道pool会自己管理?可能看了pool后就明白了。
代码:
void *ngx_array_push(ngx_array_t *a)
{  
    void        *elt, *new;
    size_t       size;
    ngx_pool_t  *p;
   
    if (a->nelts == a->nalloc) {
       
        /* the array is full */
       
        size = a->size * a->nalloc;
       
        p = a->pool;
       
        if ((u_char *) a->elts + size == p->d.last
            && p->d.last + a->size <= p->d.end)
        {  
            /*
             * the array allocation is the last in the pool
             * and there is space for new allocation
             */
           
            p->d.last += a->size;
            a->nalloc++;
       
        } else {
            /* allocate a new array */
           
            new = ngx_palloc(p, 2 * size);
            if (new == NULL) {
                return NULL;
            }
           
            ngx_memcpy(new, a->elts, size);
            a->elts = new;
            a->nalloc *= 2;
        }
    }
   
    elt = (u_char *) a->elts + a->size * a->nelts;
    a->nelts++;
   
    return elt;
}
(4)void *ngx_array_push_n(ngx_array_t *a, ngx_uint_t n)
   与ngx_array_push()函数功能类似。ngx_array_push_n()是压n个元素,ngx_array_push()压入一个元
素。
(5)void ngx_array_destroy(ngx_array_t *a)
   将分配给a的内存还给pool(a中有pool的指针)
阅读(1339) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~