IPC Produce and Consume using Stack - 01

The producerconsumer problem(also known as the bounded-buffer problem) is a classic example of a multi-process synchronization problem. The problem describes two processes, the producer and the consumer, who share a common, fixed-size buffer used as a queue. The producer's job is to generate data, put it into the buffer, and start again. At the same time, the consumer is consuming the data (i.e., removing it from the buffer), one piece at a time.Use the Stack concept and demonstrate the producer consumer operation.

Input format
1 -> Producing the item
2-> Consuming the item
3-> Exit

If the stack is empty print "Buffer is empty"
If the stack is full print "Buffer is full"

Refer the sample test cases.


#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\n2.Consumer\n3.Exit");
while(1)
{
//printf("\nEnter your choice:");
scanf("%d",&n);
switch(n)
{
case 1: if((mutex==1)&&(empty!=0))
producer();
else
printf("\nBuffer is full");
break;
case 2: if((mutex==1)&&(full!=0))
consumer();
else
printf("\nBuffer 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);
mutex=signal(mutex);
}

void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
}

Comments