先贴一段代码,有时间再来分析:
- #include <stdlib.h>
- #include <stdio.h>
- #include <pthread.h>
- #include <string.h>
- #include <sys/types.h>
- #include <unistd.h>
- #define MAX_LEN 10
- #define OFF 0x0
- #define ON ~OFF
- #define unlikely(x) __builtin_expect(!!(x), 0)
- struct node {
- struct node *pre, *next;
- u_int32_t state;
- };
- struct _block {
- u_int32_t insert_index;
- u_int32_t remove_index;
- struct node list[MAX_LEN];
- } block;
- void init_list(struct node *list, int num)
- {
- int i;
- memset(list, 0, sizeof(*list) * num);
- for(i = 1; i < MAX_LEN - 1; i++) {
- list[i].next = &list[i+1];
- list[i].pre = &list[i-1];
- }
- list[0].next = &list[1];
- list[0].pre = &list[MAX_LEN - 1];
- list[MAX_LEN - 1].next = &list[0];
- list[MAX_LEN - 1].pre = &list[MAX_LEN - 2];
- }
- void * producer_func(void *param)
- {
- while(1) {
- if(block.insert_index == block.remove_index \
- && block.list[block.insert_index].state == ON) {
- continue;
- }
- block.list[block.insert_index].state = ON;
- if(unlikely(++block.insert_index == MAX_LEN))
- block.insert_index = 0;
- }
- }
- void * customer_func(void *param)
- {
- while(1) {
- if(block.insert_index == block.remove_index \
- && block.list[block.remove_index].state == OFF) {
- continue;
- }
- block.list[block.remove_index].state = OFF;
- if(unlikely(++block.remove_index == MAX_LEN))
- block.remove_index = 0;
- }
- }
- int main(void)
- {
- pthread_t tid1, tid2;
- block.insert_index = block.remove_index = 0;
- init_list(block.list, MAX_LEN);
- pthread_create(&tid1, NULL, customer_func, NULL);
- pthread_create(&tid2, NULL, producer_func, NULL);
- while(1)
- sleep(10);
- return 0;
- }