Os Lab - 6
Os Lab - 6
Os Lab - 6
Output:
AIM : Write a c program to implement Producer-Consumer Problem.
Name: Producer-Consumer problem
Description:The producer-consumer problem is a classic synchronization and
concurrency problem in computer science and operating systems. It illustrates a scenario
where two types of processes, known as producers and consumers, share a common,
finite-size buffer or data structure.
Producer: These are processes or threads responsible for generating data or items and
placing them into a shared buffer. Producers work independently and may produce items at
varying rates.
Consumer: Consumers are processes or threads that retrieve and process the items from the
shared buffer. Like producers, consumers work independently and may consume items at
different rates.
Shared Buffer: The shared buffer is a finite-size data structure where producers deposit
items and consumers retrieve items. It acts as a bridge between producers and consumers,
allowing them to communicate and synchronize their activities.
Program:
#include <stdio.h>
#include <stdlib.h>
int mutex = 1;
int full = 0;
int empty = 10, x = 0;
void producer()
{
--mutex;
++full;
--empty;
x++;
printf("\nProducer produces" "item %d",x);
++mutex;}
void consumer()
{
--mutex;
--full;
++empty;
printf("\nConsumer consumes ""item %d",
x);
x--;
++mutex;
}
int main()
{
int n, i;
printf("\n1. Press 1 for Producer"
"\n2. Press 2 for Consumer"
"\n3. Press 3 for Exit");
#pragma omp critical
for (i = 1; i > 0; i++) {
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;
}
}
}
Output: