Producer Consumer Using Semaphores in C

Subject: OS (Operating Systems)

Contributed By: Nunugoppula Ajay

Created At: March 10, 2025

Question:


Write a C Program for Producer Consumer Problem Using Semaphores in C

Explanation Video:

Custom Image

Explanation:

 

Source Code:
#include <stdio.h>
#include <stdlib.h>
#include <semaphore.h>
#include <pthread.h>
sem_t mutex;
sem_t full;
sem_t empty;
int data = 0;
void *producer(void *param){
    sem_wait(&empty);
    sem_wait(&mutex);
    data++;
    printf("\nProducer produces item number: %d\n", data);
    sem_post(&mutex);
    sem_post(&full);
    return NULL;
}
void *consumer(void *param){
    sem_wait(&full);
    sem_wait(&mutex);
    printf("\nConsumer consumes item number: %d.\n", data);
    data--;
    sem_post(&mutex);
    sem_post(&empty);
    return NULL;
}
int main(){
    int n;
    pthread_t prod_thread, cons_thread;
    sem_init(&mutex, 0, 1);
    sem_init(&full, 0, 0);
    sem_init(&empty, 0, 5);
    printf("\n1. Enter 1 for Producer"
           "\n2. Enter 2 for Consumer"
           "\n3. Enter 3 to Exit");
    while (1){
        printf("\nEnter your choice: ");
        scanf("%d", &n);
        switch (n){
            case 1:
                if (pthread_create(&prod_thread, NULL, producer, NULL) != 0){
                    printf("Error creating producer thread\n");
                }
                pthread_join(prod_thread, NULL);
                break;
            case 2:
                if (pthread_create(&cons_thread, NULL, consumer, NULL) != 0){
                    printf("Error creating consumer thread\n");
                }
                pthread_join(cons_thread, NULL);
                break;
            case 3:
                sem_destroy(&mutex);
                sem_destroy(&full);
                sem_destroy(&empty);
                exit(0);
                break;
                default:
                    printf("Invalid choice. Please try again.\n");
        }
    }
    return 0;
}
Share this Article & Support Us:
Status
printf('Loading...');