1.基础知识
1).生产者消费模型中存在3种关系:
a.生产者与生产者之间是互斥的;
b.消费者与消费者之间是互斥的;
c.生产者与消费者之间是同步与互斥的;
2).生产者与消费者的场所,这儿我们选择单链表。
2.内容:多生产者生产一个结构体串在链表的表尾上,多消费者从表头取走结构体。
3.代码实现
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<pthread.h> 4 5 typedef struct list 6 { 7 int _data; 8 struct list* _next; 9 }product_list; 10 product_list* head=NULL; 11 12 static pthread_mutex_t lock=PTHREAD_MUTEX_INITIALIZER; //加锁 13 static pthread_cond_t need_product=PTHREAD_COND_INITIALIZER; 14 15 product_list* createNode(int data) 16 { 17 product_list* tmp=malloc(sizeof(product_list)); 18 tmp->_data=data; 19 tmp->_next=NULL; 20 return tmp; 21 } 22 void InitList(product_list** pHead) //&引用 23 { 24 *pHead=createNode(0); 25 } 26 void PushBack(product_list* pHead,int data) 27 { 28 product_list* tail=pHead; 29 while(tail->_next!=NULL) 30 { 31 tail=tail->_next; 32 } 33 product_list* new=createNode(data); 34 tail->_next=new; 35 printf("product data is:%d\n",new->_data); 36 } 37 void PopFront(product_list* pHead) 38 { 39 product_list* tmp=pHead->_next; 40 // product_list* tmp=pHead; 41 pHead->_next=pHead->_next->_next; 42 pHead=pHead->_next; 43 tmp->_next=NULL; //遗忘 44 printf("consumer data is:%d\n",tmp->_data); 45 free(tmp);//遗忘 46 tmp=NULL; 47 } 48 void* product(void* arg) 49 { 50 int i=0; 51 for(;i<10;i++) 52 { 53 pthread_mutex_lock(&lock); 54 PushBack(head,i); 55 pthread_mutex_unlock(&lock); 56 pthread_cond_signal(&need_product); 57 printf("call consumer!product success!\n"); 58 sleep(1); 59 } 60 } 61 void* consumer(void* arg) 62 { 63 while(1) 64 { 65 pthread_mutex_lock(&lock); 66 while(head->_next==NULL) 67 { 68 pthread_cond_wait(&need_product,&lock); 69 } 70 PopFront(head); 71 pthread_mutex_unlock(&lock); 72 printf("comsumer success!\n"); 73 } 74 return NULL; 75 } 76 int main() 77 { 78 InitList(&head); 79 pthread_t product1; 80 pthread_t product2; 81 pthread_t product3; 82 pthread_t consumer1; 83 pthread_t consumer2; 84 pthread_t consumer3; 85 86 pthread_create(&product1,NULL,product,NULL); 87 pthread_create(&product2,NULL,product,NULL); 88 pthread_create(&product3,NULL,product,NULL); 89 pthread_create(&consumer1,NULL,consumer,NULL); 90 pthread_create(&consumer2,NULL,consumer,NULL); 91 pthread_create(&consumer3,NULL,consumer,NULL); 92 93 pthread_join(product1,NULL); 94 pthread_join(product2,NULL); 95 pthread_join(product3,NULL); 96 pthread_join(consumer1,NULL); 97 pthread_join(consumer2,NULL); 98 pthread_join(consumer3,NULL); 99 100 return 0; 101 } //makefile 1 test:test.c 2 gcc -o $@ $^ -lpthread 3 .PHONY:clean 4 clean: 5 rm -f test
输出结果:
本文出自 “sunshine225” 博客,请务必保留此出处http://10707460.blog.51cto.com/10697460/1766910
原文地址:http://10707460.blog.51cto.com/10697460/1766910