-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProducerConsumerProb.c
68 lines (60 loc) · 1006 Bytes
/
ProducerConsumerProb.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
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#define bufferSize 5
int in = 0;
int out = 0;
int buffer[bufferSize];
int count = 0;
int S = 1;
int n1 = 0;
int n2 = 0;
void wait()
{
while (S <= 0)
;
S--;
}
void signal()
{
S++;
}
void *producer(void *arg)
{
while (n1 < 10)
{
while ((in + 1) % bufferSize == out)
;
wait();
buffer[in] = ++count;
printf("Producer produced:%d\n", buffer[in]);
in = (in + 1) % bufferSize;
n1++;
sleep(1);
signal();
}
}
void *consumer(void *arg)
{
while (n2 < 10)
{
while (in == out)
;
wait();
int op = buffer[out];
printf("Consumer consumed:%d\n", buffer[out]);
out = (out + 1) % bufferSize;
n2++;
sleep(1);
signal();
}
}
void main()
{
pthread_t producerTh;
pthread_t consumerTh;
pthread_create(&producerTh, NULL, producer, NULL);
pthread_create(&consumerTh, NULL, consumer, NULL);
pthread_join(producerTh, NULL);
pthread_join(consumerTh, NULL);
}