生产者和消费者问题(1)

前提:本文是基于Linux系统下的学习

 1 //实现消费者和生产者的概念
 2 //数据结构  链表
 3 //生产者将新的产品放置到链表的头部
 4 //消费者从链表的头部取出数据
 5 //生产过剩没有考虑
 6 #include <stdio.h>
 7 #include <pthread.h>
 8 #include <stdlib.h>
 9 #include <time.h>
10 #include <unistd.h>
11 
12 struct node;
13 typedef struct node node_t;
14 typedef struct node* list_t;
15 struct node{
16     int data;
17     node_t *next;
18 };
19 
20 list_t head=NULL;//指向链表的头指针
21 //静态初始化mutex锁
22 pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
23 //静态初始化一个条件变量
24 pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
25 //生产者线程
26 void* product(void *arg){
27     node_t *new;
28     while(1){
29         //产生一个新的节点
30         new=(list_t)malloc(sizeof(node_t));
31         new->data=rand()%1000+1;
32         new->next=NULL;
33         printf("p:%d\n",new->data);
34         
35         //加锁
36         pthread_mutex_lock(&mutex);
37         //将新节点插入到链表的头部
38         new->next=head;
39         head=new;
40         //解锁
41         pthread_mutex_unlock(&mutex);
42         pthread_cond_signal(&cond);
43         sleep(rand()%5+1);    
44     }
45 }
46 
47 //消费者线程
48 void* consume(void *arg){
49     list_t tmp;
50     while(1){
51         //加锁
52         pthread_mutex_lock(&mutex);
53         if(head==NULL){
54             //阻塞等待生产者生产
55             pthread_cond_wait(&cond,&mutex);//解锁  等待  重新获取锁
56         }
57         tmp=head;
58         head=head->next;
59         //解锁
60         pthread_mutex_unlock(&mutex);
61         //消费
62         printf("c:%d\n",tmp->data);
63         free(tmp);
64         tmp=NULL;
65 
66         sleep(rand()%5+1);
67     }
68 }
69 
70 int main(){
71     srand(time(NULL));
72     pthread_t pid,cid;
73     //创建两个线程 pid生产者;cid消费者
74     pthread_create(&pid,NULL,product,NULL);    
75     pthread_create(&cid,NULL,consume,NULL);
76 
77     //阻塞等待线程汇合
78     pthread_join(pid,NULL);
79     pthread_join(cid,NULL);
80     //销毁mutex锁
81     pthread_mutex_destroy(&mutex);
82     //销毁条件变量
83     pthread_cond_destroy(&cond);
84     
85     return 0;
86 }

猜你喜欢

转载自www.cnblogs.com/qiuyuwutong/p/9385318.html