queue(3)--freebsd中的queue结构使用

前几天看代码,发现有类似这样的结构:

 

[c-sharp]  view plain copy
  1. TAILQ_FOREACH(np, &head, entries){  
  2.     printf("%d  %d/n", np->a1, np->a2);  
  3. }  
 

我没太多代码编写经验,初读的时候能模糊知道和for_each()函数类似,但十分好奇是如何实现了,后来在发现引用了queue.h头文件,是freebsd里定义的一头文件,采用宏定义的形式实现了4种基本的数据结构,没做太多深入的理解,我简单把其中的Tail queue拿出来用了用。

[cpp]  view plain copy
  1. #include "queue.h"  
  2. typedef struct test_num_ test_num;  
  3. struct test_num_{  
  4.     unsigned int a1:3;  
  5.     unsigned int a2:1;  
  6.     TAILQ_ENTRY(test_num) entries;     /* Tail queue. */  
  7. };  
  8. int main()  
  9. {  
  10.     test_num *n1, *n2, *n3, *np;  
  11.     TAILQ_HEAD(tailhead, test_num) head;  
  12.     struct tailhead *headp = &head;         /* Tail queue head.  = &head */  
  13.     TAILQ_INIT(&head);                      /* Initialize the queue. */  
  14.     n1 = malloc(sizeof(test_num));      /* Insert at the head. */  
  15.     n1->a1 = 1;  
  16.     n1->a2 = 5;  
  17.     TAILQ_INSERT_HEAD(&head, n1, entries);  
  18.     n3 = malloc(sizeof(test_num));      /* Insert at the tail. */  
  19.     n3->a1 = 3;  
  20.     n3->a2 = 0;  
  21.     TAILQ_INSERT_TAIL(&head, n3, entries);  
  22.     n2 = malloc(sizeof(test_num));      /* Insert after. */  
  23.     n2->a1 = 2;  
  24.     TAILQ_INSERT_AFTER(&head, n1, n2, entries);  
  25.     /* Forward traversal. */  
  26.     for (np = head.tqh_first; np != NULL; np = np->entries.tqe_next){  
  27.         printf("%d  %d/n", np->a1, np->a2);  
  28.     }  
  29.     TAILQ_FOREACH(np, &head, entries){  
  30.         printf("%d  %d/n", np->a1, np->a2);  
  31.     }  
  32.     /* Delete. 我纳闷的是,这只是在queue中删除了元素,但n1,n2,n3对象并未释放,需要注意 */  
  33.     while (head.tqh_first != NULL)  
  34.         TAILQ_REMOVE(&head, head.tqh_first, entries);  
  35.     //确实没有释放  
  36.     printf("%d  %d/n", n3->a1, n3->a2);  
  37.     free(n1);  
  38.     free(n2);  
  39.     free(n3);  
  40.     getchar();  
  41. }  
 

 

其中有个特别的地方是struct结构体中的形式:unsigned int a1:3;,它指明a1的最大值只能是2的N次方减1(2^N-1)

另外有个注意的地方当给a2赋值5、0和未初始化的情况下,它的值的情况。

 

参考:

http://blogold.chinaunix.net/u/21842/showart_142295.html

http://topic.csdn.net/u/20090725/21/3310fdf5-f60f-4541-a98d-c629ad92a3a4.html

转自 http://blog.csdn.net/cumirror/article/details/6283655

你可能感兴趣的:(queue(3)--freebsd中的queue结构使用)