Lab-3
Develop a program to simulate producer consumer problem using
semaphores
Producer consumer problem(Bounded buffer problem)
Semaphores
• Software based solution to the critical section problem
• Semaphore is an integer variable that, apart from initialization , is
accessed only through two standard operations: wait() and signal()
• The wait() operation was originally termed P(proberen-to test)
• The signal() was originally called V(verhogen-to increment)
Definitions of wait and signal
wait(S) signal(S)
{ {
while S<=0 S++;
;//no op }
S--;
}
Types of semaphores
• Counting semaphores-Range over an unrestricted domain
• Binary semaphores(mutex)-range between 0 and 1
int S = 1;
int F = 0;
int E = 5, x = 0;
void signal(int *S)
{
++S;
return;
}
void wait(int *S)
{
--S;
return;
}
void producer()
{
wait(&S);
++F;
--E;
x++;
printf("\nProducer produces item %d",x);
signal(&S);
}
void consumer()
{
wait(&S);
--F;
++E;
printf("\nConsumer consumes item %d",x);
x--;
signal(&S);
}
int main()
{
int n, i;
printf("\n1. Press 1 for Producer\n2. Press 2 for Consumer\[Link] 3
for Exit\n");
for (i = 1; i > 0; i++)
{
printf("\nEnter your choice:");
scanf("%d", &n);
switch (n)
{
case 1:
if ((S == 1) && (E != 0))
{
producer();
}
else
{
printf("Buffer is full!");
}
break;
case 2:
if ((S == 1) && (F != 0))
{
consumer();
}
else
{
printf("Buffer is empty!");
}
break;
case 3:
exit(0);
break;
}
}
}