nginx之数据结构list结构
<DIV><DIV class=cnt id=blog_text>在任何一套成熟的C语言写的服务器或者语言或者应用里都包含有一些基本的数据结构操作,<BR><BR>一般是 array、list、hash、buf等,剖析nginx的list是下面这种结构:<BR><BR>元素本身的长度是size,每个桶可承担n项,那么当你插入第n+1个元素的时候,要创建一个新桶。因此nginx的list内部元素是定长结构。<BR><BR>例如:<BR><BR>mctx->variables = ngx_list_create(r->pool, 4,<BR> sizeof(ngx_http_ssi_var_t));<BR><BR>前提是nginx的所有内存操作都建立在pool基础上,其中每4个元素为一个桶,当插入第五个元素的时候新建一个桶。nginx把这种桶成为part。应该就是一个子列表的意思。<BR><BR>下面具体来看和list有关的结构和方法:<BR><BR>typedef struct ngx_list_part_s ngx_list_part_t;<BR><BR>struct ngx_list_part_s {<BR> void *elts;<BR> ngx_uint_t nelts;<BR> ngx_list_part_t *next;<BR>};<BR><BR>这是一个桶(子列表),elts是首元素的指针,nelts是元素总个数,next是下一个桶的指针。<BR><BR>typedef struct {<BR> ngx_list_part_t *last;<BR> ngx_list_part_t part;<BR> size_t size;<BR> ngx_uint_t nalloc;<BR> ngx_pool_t *pool;<BR>} ngx_list_t;<BR><BR>这是list的上层结构,last是最后一个桶的指针,part是第一个桶,size是每个元素的大小,nalloc是每个桶里存放多少个元素,当nelts和nalloc相等表明子列表已经到达了桶底。需要分配一个新桶来使用。pool是这个列表所基于的pool地址。<BR><BR>列表一共有三种操作:<BR><BR>ngx_list_create(); //创建及初始化队列<BR>ngx_list_init(); //初始化队列<BR>ngx_list_push(); //找到下一个插入位置的指针并返回<BR><BR>nginx的list遍历和list表的实际插入并不是在这三个函数中完成的,而是散落在外面,可能是作者觉得这样足够灵活。<BR><BR>由于空间是提前分配的,因此ngx_list_push()实际上返回的只是一段定长空间的指针,我们举个例子:<BR><BR>遍历列表<BR><BR>part = &cycle->open_files.part;<BR> file = part->elts;<BR><BR> for (i = 0; /* void */ ; i++) {<BR><BR> if (i >= part->nelts) {<BR> if (part->next == NULL) {<BR> break;<BR> }<BR> part = part->next;<BR> file = part->elts;<BR> i = 0;<BR> }<BR><BR> if (full.len != file.name.len) {<BR> continue;<BR> }<BR><BR> if (ngx_strcmp(full.data, file.name.data) == 0) {<BR> return &file;<BR> }<BR> }<BR><BR>由于存在桶的概念,所以遍历需要一个for循环和一个if语句双重嵌套,以满足当一个桶遍历结束后,遍历下一个桶。<BR><BR>插入一个元素<BR><BR>file = ngx_list_push(&cycle->open_files);<BR> if (file == NULL) {<BR> return NULL;<BR> }<BR><BR> if (name) {<BR> file->fd = NGX_INVALID_FILE;<BR> file->name = full;<BR><BR> } else {<BR> file->fd = ngx_stderr_fileno;<BR> file->name.len = 0;<BR> file->name.data = NULL;<BR> }<BR><BR> file->buffer = NULL;<BR><BR> return file;<BR><BR>首先返回file指针,然后对file进行赋值。</DIV><BR>本文摘自:</DIV>
<DIV><a href="http://hi.baidu.com/langwan/blog/item/02eea1ef8698481efdfa3cd0.html" target="_blank">http://hi.baidu.com/langwan/blog/item/02eea1ef8698481efdfa3cd0.html</A></DIV>
<DIV>非常感谢langwan先生给我们的帮助</DIV>
页:
[1]