[go: up one dir, main page]

0% found this document useful (0 votes)
5 views2 pages

Producer - Consumer - Program Producer - Consumer - Program

The document presents a C program implementing the Producer-Consumer problem using semaphores for synchronization. It allows users to choose between producing and consuming items in a buffer, managing the states of mutex, full, and empty. The program continues to run until the user chooses to exit.

Uploaded by

mdateeq807
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views2 pages

Producer - Consumer - Program Producer - Consumer - Program

The document presents a C program implementing the Producer-Consumer problem using semaphores for synchronization. It allows users to choose between producing and consuming items in a buffer, managing the states of mutex, full, and empty. The program continues to run until the user chooses to exit.

Uploaded by

mdateeq807
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

Producer-Consumer Program in C

#include <stdio.h>
#include <stdlib.h>

int mutex = 1, full = 0, empty = 3, x = 0;

int wait(int);
int signal(int);
void producer();
void consumer();

int main() {
int n;

printf("\n1. Producer\n2. Consumer\n3. Exit\n");

while (1) {
printf("\nEnter your choice: ");
scanf("%d", &n);

switch (n) {
case 1:
if ((mutex == 1) && (empty != 0))
producer();
else
printf("\nBuffer is full!\n");
break;

case 2:
if ((mutex == 1) && (full != 0))
consumer();
else
printf("\nBuffer is empty!\n");
break;

case 3:
exit(0);

default:
printf("\nInvalid choice! Please try again.\n");
}
}

return 0;
}

int wait(int s) {
return (--s);
}

int signal(int s) {
return (++s);
}

void producer() {
mutex = wait(mutex);
empty = wait(empty);
full = signal(full);
x++;
printf("\nProducer produces item %d\n", x);
mutex = signal(mutex);
}

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

You might also like