Menu

Operating Systems [ Lab Programs ]


Aim:

  Write a C program to implement the Producer - Consumer problem using semaphores using UNIX/LINUX system calls.

Solution :

DESCRIPTION:

The producer consumer problem is a synchronization problem. There is a fixed size buffer and the producer produces items and enters them into the buffer. The consumer removes the items from the buffer and consumes them. A producer should not produce items into the buffer when the consumer is consuming an item from the buffer and vice versa. So the buffer should only be accessed by the producer or consumer at a time.

PROGRAM: ( producer_consumer.c )

 
#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("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);
mutex=signal(mutex);
}
void consumer()
{
mutex=wait(mutex);
full=wait(full);
empty=signal(empty);
printf("\nConsumer consumes item %d",x);
x--;
mutex=signal(mutex);
}

OUTPUT:

 
$ gcc producer_consumer.c
$ ./a.out

1.Producer
2.Consumer
3.Exit
Enter your choice:1

Producer produces the item 1
Enter your choice:2

Consumer consumes item 1
Enter your choice:2
Buffer is empty!!
Enter your choice:1

Producer produces the item 1
Enter your choice:1

Producer produces the item 2
Enter your choice:2

Consumer consumes item 2
Enter your choice:2

Consumer consumes item 1
Enter your choice:2
Buffer is empty!!
Enter your choice:3




Related Content :

1. Write C programs to simulate the following CPU Scheduling algorithms
a) FCFS
b) SJF
c) RoundRobin
d) priority    View Solution


2. Write programs using the I/O system calls of UNIX/LINUX operating system (open, read, write, close,fcntl, seek, stat, opendir, readdir)    View Solution


3. Write a C program to simulate Bankers Algorithm for Deadlock Avoidance and Prevention.    View Solution


4. Write a C program to implement the Producer – Consumer problem using semaphores using UNIX/LINUX system calls.   View Solution


5. Write C programs to illustrate the following IPC mechanisms
a) Pipes
b) FIFOs
c) Message Queues
d) Shared Memory.    View Solution


6. Write C programs to simulate the following memory management techniques
a) Paging
b) Segmentation    View Solution


7. Write C programs to simulate Page replacement policies
a) FCFS
b) LRU
c) Optimal    View Solution