-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsemaphore.c
More file actions
90 lines (88 loc) · 1.76 KB
/
semaphore.c
File metadata and controls
90 lines (88 loc) · 1.76 KB
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
#include<stdio.h>
#include<stdlib.h>
#include <stdbool.h>
int sem=1,full,empty,buffer[20];
int front=-1,rear=-1;
int wait(int val)
{
return (--val);
}
int signal(int val)
{
return (++val);
}
void printbuffer()
{
printf("\n Buffer :");
for(int i=front;i<=rear;i++)
printf(" %d ",buffer[i]);
}
void insert(int item)
{
if(rear==-1)
front++;
buffer[++rear]=item;
}
int delete()
{
return(buffer[front++]);
}
void producer(int item)
{
empty=wait(empty);
sem=wait(sem);
printf("\n Producer produces %d ",item);
insert(item);
sem=signal(sem);
full=signal(full);
}
void consumer()
{
full=wait(full);
sem=wait(sem);
int item=delete();
printf("\n Consumer Consumes %d ",item);
sem=signal(sem);
empty=signal(empty);
}
void main()
{
int n,size,item;
printf("Enter the size of Buffer :");
scanf("%d",&size);
full=0;
empty=size;
printf("\n Producer Consumer Problem");
printf("\n 1.Produce");
printf("\n 2.Consume");
printf("\n 3.Exit");
while(true){
printf("\n\n Enter your choice:");
scanf("%d",&n);
switch(n){
case 1:
if((sem==1)&&(empty!=0)){
int item = rand() % 50;
producer(item);
printbuffer();
}
else
{
printf("\n Buffer is full!!");
}
break;
case 2:
if((sem==1)&&(full!=0))
{
consumer();
printbuffer();
}
else{
printf("\n Buffer is empty!!");
}
break;
case 3:
exit(0);
}
}
}