-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpc1.c
126 lines (112 loc) · 2.52 KB
/
pc1.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<pthread.h>
#include<ctype.h>
#define size 4
#define count 8
char buff[3][size];
int in[3]={0,0,0},out[3]={0,0,0};
//检查缓冲区是否为空
int check_empty(int num)
{
return in[num]==out[num];
}
//检查缓冲区是否已满
int check_full(int num)
{
return (in[num]+1)%size==out[num];
}
//入缓冲区
void in_set(int num,char item)
{
buff[num][in[num]]=item;
in[num]=(in[num]+1)%size;
}
//出缓冲区
char out_set(int num)
{
char item;
item=buff[num][out[num]];
out[num]=(out[num]+1)%size;
return item;
}
pthread_mutex_t mutex_buff1,mutex_buff2;
pthread_cond_t wait_empty_buff1,wait_empty_buff2;
pthread_cond_t wait_full_buff1,wait_full_buff2;
//消费者
void *consume(void *arg)
{
int i;
char item;
for (i=0;i<count;i++)
{
pthread_mutex_lock(&mutex_buff2);
while (check_empty(2))
pthread_cond_wait(&wait_full_buff2,&mutex_buff2);
item = out_set(2);
printf(" consume item: %c\n",item);
pthread_cond_signal(&wait_empty_buff2);
pthread_mutex_unlock(&mutex_buff2);
}
return NULL;
}
//计算者
void *calculate(void *arg)
{
int i;
char item;
for (i=0;i<count;i++)
{
pthread_mutex_lock(&mutex_buff1);
while(check_empty(1))
pthread_cond_wait(&wait_full_buff1,&mutex_buff1);
item=out_set(1);
pthread_cond_signal(&wait_empty_buff1);
pthread_mutex_unlock(&mutex_buff1);
pthread_mutex_lock(&mutex_buff2);
while(check_full(2))
pthread_cond_wait(&wait_empty_buff2,&mutex_buff2);
in_set(2,toupper(item));
printf(" calculate item: %c\n",toupper(item));
pthread_cond_signal(&wait_full_buff2);
pthread_mutex_unlock(&mutex_buff2);
}
return NULL;
}
//生产者
void *produce(void *arg)
{
int i;
char item;
for (i=0;i<count;i++)
{
pthread_mutex_lock(&mutex_buff1);
while (check_full(1))
pthread_cond_wait(&wait_empty_buff1,&mutex_buff1);
item='a'+i;
in_set(1,item);
printf("produce item: %c\n",item);
pthread_cond_signal(&wait_full_buff1);
pthread_mutex_unlock(&mutex_buff1);
}
return NULL;
}
int main()
{
pthread_t tid1,tid2,tid3;
pthread_mutex_init(&mutex_buff1,NULL);
pthread_mutex_init(&mutex_buff2,NULL);
pthread_cond_init(&wait_empty_buff1,NULL);
pthread_cond_init(&wait_empty_buff2,NULL);
pthread_cond_init(&wait_full_buff1,NULL);
pthread_cond_init(&wait_full_buff2,NULL);
pthread_create(&tid1,NULL,consume,NULL);
pthread_create(&tid2,NULL,produce,NULL);
pthread_create(&tid3,NULL,calculate,NULL);
//calculate(NULL);
pthread_join(tid2,NULL);
pthread_join(tid1,NULL);
pthread_join(tid3,NULL);
return 0;
}