循环队列可以实现一个生产者与一个消费者模型, 不使用锁。
循环队列:容量大小为10
生产者线程:把从0递增的整数依次push到队列,队列满了就等1s(尾部不存储,也就是最大存9个数)。
消费者线程:每3s从队列pop一个元素。
[xiongli@localhost data_struct]$ ./a.out
push 0 at data[0]
push 1 at data[1]
push 2 at data[2]
push 3 at data[3]
push 4 at data[4]
push 5 at data[5]
push 6 at data[6]
push 7 at data[7]
push 8 at data[8]
the queue is full!
the queue is full!
the queue is full!
pop 0 at data[0]
push 9 at data[9]
the queue is full!
the queue is full!
the queue is full!
pop 1 at data[1]
push 10 at data[0]
the queue is full!
the queue is full!
the queue is full!
pull 2 at data[2]
push 11 at data[1]
the queue is full!
the queue is full!
the queue is full!
pop 3 at data[3]
push 12 at data[2]
the queue is full!
the queue is full!
the queue is full!
pop 4 at data[4]
push 13 at data[3]
the queue is full!
the queue is full!
the queue is full!
#include <stdio.h> #include <pthread.h> #define QUEUE_SIZE 10 struct EnQueue { unsigned int nHead; unsigned int nTail; int data[QUEUE_SIZE]; } Queue; int isFull() { if((Queue.nTail+1) % QUEUE_SIZE == Queue.nHead) return 1; else return 0; } void* push() { int i=0; while(1) { if(isFull()) { printf("the queue is full!\n"); sleep(1); continue; } Queue.data[Queue.nTail] = i++; printf("push %d at data[%d]\n",Queue.data[Queue.nTail],Queue.nTail); Queue.nTail = (Queue.nTail+1) % QUEUE_SIZE; //设置尾部 } return NULL; } void* pop() { int n; while(1) { sleep(3); if(Queue.nHead != Queue.nTail) { n = Queue.data[Queue.nHead]; printf("\t\tpull %d at data[%d]\n",n,Queue.nHead); Queue.nHead = (Queue.nHead+1) % QUEUE_SIZE; //设置头部 } } printf("pull exit\n"); return NULL; } int main() { pthread_t tid1,tid2; pthread_create(&tid1,NULL,push,NULL); pthread_create(&tid2,NULL,pop,NULL); pthread_join(tid1,NULL); pthread_join(tid2,NULL); }