Experiment No. 12: AIM: Implementation of Producer-Consumer Problem Using Semaphore in C. Theory
Experiment No. 12: AIM: Implementation of Producer-Consumer Problem Using Semaphore in C. Theory
12
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 signal()
Signal (S)
{
S++;
}
Producer - Consumer Problem
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);
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