Untitled
#include <stdio.h> int mutex = 1, full = 0, empty = 5, x = 0; // Assuming buffer size is 5 void producer(); void consumer(); int wait(int); int signal(int); 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("Buffer is full\n"); } break; case 2: if ((mutex == 1) && (full != 0)) { consumer(); } else { printf("Buffer is empty\n"); } break; case 3: return 0; default: printf("Invalid choice\n"); break; } } return 0; } int wait(int s) { return (--s); } int signal(int s) { return (++s); } void producer() { mutex = wait(mutex); // Lock mutex full = signal(full); // Increment the full count empty = wait(empty); // Decrement the empty count x++; // Produce an item printf("Producer produces item %d\n", x); mutex = signal(mutex); // Unlock mutex } void consumer() { mutex = wait(mutex); // Lock mutex full = wait(full); // Decrement the full count empty = signal(empty); // Increment the empty count printf("Consumer consumes item %d\n", x); x--; // Consume an item mutex = signal(mutex); // Unlock mutex }
Leave a Comment