0 votes
104 views
in Operating System by (420 points)
edited
Program to simulate producer and consumer problem using semaphores

1 Answer

0 votes
by (98.9k points)
selected by
 
Best answer
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

#define BUFFER_SIZE 3

int buffer[BUFFER_SIZE];
int in = 0, out = 0;

bool isBufferEmpty() {
    return in == out;
}

bool isBufferFull() {
    return (in + 1) % BUFFER_SIZE == out;
}

void produce(int item) {
    buffer[in] = item;
    in = (in + 1) % BUFFER_SIZE;
}

int consume() {
    int item = buffer[out];
    out = (out + 1) % BUFFER_SIZE;
    return item;
}

void producer() {
    int item;
    printf("Enter item to produce: ");
    scanf("%d", &item);
    if (isBufferFull()) {
        printf("Buffer is full, cannot produce.\n");
        return;
    }
    produce(item);
    printf("Produced item %d.\n", item);
}

void consumer() {
    if (isBufferEmpty()) {
        printf("Buffer is empty, cannot consume.\n");
        return;
    }
    int item = consume();
    printf("Consumed item %d.\n", item);
}

int main() {
    int choice;
    while (true) {
        printf("\n1. Produce\n2. Consume\n3. Exit\nEnter your choice: ");
        scanf("%d", &choice);
        switch(choice) {
            case 1: producer(); break;
            case 2: consumer(); break;
            case 3: exit(0);
            default: printf("Invalid choice.\n"); break;
        }
    }
    return 0;
}

Related questions

0 votes
1 answer 95 views
0 votes
1 answer 102 views

Doubtly is an online community for engineering students, offering:

  • Free viva questions PDFs
  • Previous year question papers (PYQs)
  • Academic doubt solutions
  • Expert-guided solutions

Get the pro version for free by logging in!

5.7k questions

5.1k answers

108 comments

557 users

...