nginx双向链表ngx_queue_t
ngx_queue_t是nginx中实现的双向链表,在要用到双向链表的自定义结构体中将ngx_queue_t嵌入到自定义结构体中即可。还有一个特点是ngx_queue_t不涉及到内存分配。
二、例子
下面的源码是将《深入理解nginx》第7章关于ngx_queue_t的源码整合起来。Makefile则是参考http://blog.csdn.net/livelylittlefish/article/details/6586946。
#include
#include "ngx_config.h"
#include "ngx_conf_file.h"
#include "nginx.h"
#include "ngx_core.h"
#include "ngx_string.h"
#include "ngx_palloc.h"
#include "ngx_queue.h"
volatile ngx_cycle_t *ngx_cycle;
void ngx_log_error_core(ngx_uint_t level,ngx_log_t *log, ngx_err_t err,
const char *fmt, ...)
{
}
typedef struct {
u_char*str;
ngx_queue_tqEle;
intnum;
}TestNode;
ngx_int_t compTestNode(const ngx_queue_t*a, const ngx_queue_t *b)
{
TestNode*aNode = ngx_queue_data(a, TestNode, qEle);
TestNode*bNode = ngx_queue_data(b, TestNode, qEle);
returnaNode->num > bNode->num;
}
int main()
{
ngx_queue_tqueueContainer;
ngx_queue_init(&queueContainer);
inti = 0;
TestNodenode[5];
for(; i
node[i].num= i;
}
ngx_queue_insert_tail(&queueContainer,&node[0].qEle);
ngx_queue_insert_head(&queueContainer,&node[1].qEle);
ngx_queue_insert_tail(&queueContainer,&node[2].qEle);
ngx_queue_insert_after(&queueContainer,&node[3].qEle);
ngx_queue_insert_tail(&queueContainer,&node[4].qEle);
ngx_queue_t*q;
for(q = ngx_queue_head(&queueContainer);
q!= ngx_queue_sentinel(&queueContainer);
q= ngx_queue_next(q)) {
TestNode*eleNode = ngx_queue_data(q, TestNode, qEle);
printf("%d\n",eleNode->num);
}
printf("*****sort*****\n");
ngx_queue_sort(&queueContainer,compTestNode);
for(q = ngx_queue_head(&queueContainer);
q!= ngx_queue_sentinel(&queueContainer);
q= ngx_queue_next(q)) {
TestNode*eleNode = ngx_queue_data(q, TestNode, qEle);
printf("%d\n",eleNode->num);
}
return0;
}
Makefile
CXX = gcc
CXXFLAGS += -g -Wall -Wextra
NGX_ROOT = /usr/src/nginx-1.0.4
TARGETS = test_queue
TARGETS_C_FILE = $(TARGETS).c
CLEANUP = rm -f $(TARGETS) *.o
all: $(TARGETS)
clean:
$(CLEANUP)
CORE_INCS = -I.\
-I$(NGX_ROOT)/src/core\
-I$(NGX_ROOT)/src/event\
-I$(NGX_ROOT)/src/event/modules\
-I$(NGX_ROOT)/src/os/unix\
-I$(NGX_ROOT)/objs\
NGX_PALLOC =$(NGX_ROOT)/objs/src/core/ngx_palloc.o
NGX_STRING =$(NGX_ROOT)/objs/src/core/ngx_string.o
NGX_ALLOC = $(NGX_ROOT)/objs/src/os/unix/ngx_alloc.o
NGX_QUEUE =$(NGX_ROOT)/objs/src/core/ngx_queue.o
$(TARGETS): $(TARGETS_C_FILE)
$(CXX)$(CXXFLAGS) $(CORE_INCS) $(NGX_PALLOC) $(NGX_STRING) $(NGX_ALLOC) $(NGX_QUEUE)$^ -o $@
三、总结
1、一个链表通过链表头标识,不包含用户自定义的相关数据。
以上就介绍了nginx双向链表ngx_queue_t,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。