EXPERIMENT NO.
12
AIM: Implementation of Producer- consumer problem using semaphore in C.
THEORY:
Semaphore is a special kind of integer valuable which can be initialized and can be accessed only
through 2 standard atomic operation.
1. P Operation or Wait Operation
2. V Operation or Signal Operation
The definition of wait ():
Semaphore S
Wait (S)
{
while S <= 0 ;
S--·
}
The definition of signal()
Signal (S)
{
S++;
}
Producer - Consumer Problem
i) It is classic example of multipurpose synchronization problem.
ii) The problem describes two processes, the producer and consumer, who share common
fixed size buffer.
iii) The producer job is to generable data and put it into buffer. At same time, the consumer
is consuming data.
iv) Problem is to make sure that producer won’t try to add data into the buffer if its full &
that consumer won’t try to remove data from an empty buffer.
v) The solution for produces is to either go to sleep if buffer is full. The next time consumer
remove an item from butter if the producer who start to fill buffer again same way the
consumer can go to sleep if it finds the buffer to be empty the next time if producer this
data.
ALGORITHM
PRODUCER PROCESS:
do
{
Produce an item in next produced
Wait (empty);
Wait (Plutex);
add next – producer to buffer
Signal (mutex)
Signal (full)
}
While (True)
CONSUMER PROCESS:
do
{
Wait (Full);
Wait (Mutex);
Remove on item from buffer to next consumer
…..
signal (mutex);
signal (empty);
consume the item next consumer
}
While(true);
CONCLUSION:- Producer-consumer problem is also called as bounded buffer Problem. A
buffer is shared between producer and consumer, which has fixed or limited size that can
be solved and implemented using semaphore.
PROGRAM
#include<stdio.h>
#include<stdlib.h>
int mutex=1,full=0,empty=3,x=0;
int main()
{
int n;
void producer();
void consumer();
int wait(int);
int signal(int);
printf("\n1.Producer 2.Consumer 3.Exit");
while(1)
{
printf("\nEnter your choice:");
scanf("%d",&n);
switch(n)
{
case 1: if((mutex==1)&&(empty!=0))
producer();
else
printf("Buffer is full!!");
break;
case 2: if((mutex==1)&&(full!=0))
consumer();
else
printf("Buffer is empty!!");
break;
case 3:
exit(0);
break;
}
}
return 0;
}
int wait(int s)
{
return (--s);
}
int signal(int s)
{
return(++s);
}
void producer()
{
mutex=wait(mutex);
full=signal(full);
empty=wait(empty);
x++;
printf("\nProducer produces the item %d",x);
if(x == 3)
{
printf("\nItems in buffer are: %d %d %d", x-2, x-1, x );
}
mutex=signal(mutex);
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
printf("\n Remaining items in buffer is: %d %d",x-1,x);
}
OUTPUT:-
1.Producer 2.Consumer 3.Exit
Enter your choice:1
Producer produces the item 1
Enter your choice:1
Producer produces the item 2
Enter your choice:1
Producer produces the item 3
Items in buffer are: 1 2 3
Enter your choice:2
Consumer consumes item 3
Remaining items in buffer is: 1 2