-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPCP_Rov.c
71 lines (70 loc) · 1.28 KB
/
PCP_Rov.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
#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
#include<unistd.h>
#include<time.h>
sem_t mutex,full,empty;
int buffer[5],put=0,get=0,item=1,pro[20],con[20],gitem;
void *producer(void *arg)
{
do
{
sem_wait(&empty);
sem_wait(&mutex);
buffer[put%5]=item;
int *myid = (int *)arg;
printf("PRODUCER PRODUCES ITEM => %d\n",buffer[put%5]);
item++;
put++;
sem_post(&mutex);
sem_post(&full);
sleep(3);
}
while(1);
}
void *consumer(void *arg)
{
do
{
sem_wait(&full);
sem_wait(&mutex);
gitem=buffer[get%5];
int *myid = (int *)arg;
printf("CONSUMER CONSUMES ITEM => [%d]\n",gitem);
get++;
sem_post(&mutex);
sem_post(&empty);
sleep(2);
}
while(1);
}
void main()
{
int p,c,j,k;
pthread_t a[10],b[10];
sem_init(&mutex,0,1);
sem_init(&full,0,0);
sem_init(&empty,0,5);
printf("ENTER THE NUMBER OF PRODUCERS : ");
scanf("%d",&p);
printf("ENTER THE NUMBER OF CONSUMERS : ");
scanf("%d",&c);
for(j=0;j<p;j++)
{
pro[j]=j+1;
pthread_create(&a[j],NULL,producer,(void *)&pro[j]);
}
for(k=0;k<c;k++)
{
con[k]=k+1;
pthread_create(&b[k],NULL,consumer,(void *)&con[k]);
}
for(j=0;j<p;j++)
{
pthread_join(&a[j],NULL);
}
for(k=0;k<c;k++)
{
pthread_join(&b[k],NULL);
}
}