單生產者+單消費者模式下的雙向循環鏈表之無鎖結構

先貼一段代碼,有時間再來分析:

 

  1. #include <stdlib.h>  
  2. #include <stdio.h>  
  3. #include <pthread.h>  
  4. #include <string.h>  
  5. #include <sys/types.h>  
  6. #include <unistd.h>  
  7.  
  8. #define MAX_LEN        10  
  9. #define OFF                0x0  
  10. #define ON                ~OFF  
  11.    
  12. #define unlikely(x)        __builtin_expect(!!(x), 0)  
  13.    
  14. struct node {  
  15.         struct node *pre, *next;                          
  16.         u_int32_t state;  
  17. };  
  18.    
  19. struct _block {  
  20.         u_int32_t        insert_index;  
  21.         u_int32_t        remove_index;  
  22.         struct node list[MAX_LEN];  
  23. } block;  
  24.    
  25.  
  26. void init_list(struct node *list, int num)  
  27. {  
  28.         int i;  
  29.         memset(list, 0, sizeof(*list) * num);  
  30.         for(i = 1; i < MAX_LEN - 1; i++) {  
  31.                 list[i].next = &list[i+1];  
  32.                 list[i].pre        = &list[i-1];  
  33.         }  
  34.  
  35.         list[0].next = &list[1];   
  36.         list[0].pre = &list[MAX_LEN - 1];  
  37.         list[MAX_LEN - 1].next = &list[0];  
  38.         list[MAX_LEN - 1].pre = &list[MAX_LEN - 2];  
  39. }  
  40.    
  41.  
  42.  
  43. void * producer_func(void *param)  
  44. {  
  45.         while(1) {  
  46.                 if(block.insert_index == block.remove_index  \  
  47.                         && block.list[block.insert_index].state == ON) {  
  48.                         continue;                  
  49.                 }  
  50.                 block.list[block.insert_index].state = ON;  
  51.                 if(unlikely(++block.insert_index == MAX_LEN))  
  52.                         block.insert_index = 0;  
  53.         }          
  54. }  
  55.    
  56.  
  57. void * customer_func(void *param)  
  58. {  
  59.         while(1) {  
  60.                 if(block.insert_index == block.remove_index  \  
  61.                         && block.list[block.remove_index].state == OFF) {  
  62.                         continue;                  
  63.                 }  
  64.                 block.list[block.remove_index].state = OFF;  
  65.                 if(unlikely(++block.remove_index == MAX_LEN))  
  66.                         block.remove_index = 0;  
  67.         }  
  68. }  
  69.    
  70.  
  71. int main(void)  
  72. {  
  73.         pthread_t tid1, tid2;  
  74.         block.insert_index = block.remove_index = 0;  
  75.         init_list(block.list, MAX_LEN);  
  76.    
  77.  
  78.         pthread_create(&tid1, NULL, customer_func, NULL);  
  79.         pthread_create(&tid2, NULL, producer_func, NULL);  
  80.  
  81.         while(1)   
  82.                 sleep(10);  
  83.         return 0;  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章