EXPERIMENT NO.
6:-PROCESS MANAGEMENT-SYNCHRONIZATION
AIM:-write a c program to implement solution of producer consumer problem
through semaphore
PROGRAM:-
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h> // For sleep function
#define MAX_BUFFER_SIZE 5
int buffer[MAX_BUFFER_SIZE];
int in = 0;
int out = 0;
sem_t empty, full, mutex;
void* producer(void* param) {
int item;
while (1) {
item = rand() % 100; // Produce a random item
sem_wait(&empty); // Decrease empty count (check if buffer has space)
sem_wait(&mutex); // Enter critical section to access the buffer
buffer[in] = item;
printf("Produced: %d\n", item);
in = (in + 1) % MAX_BUFFER_SIZE;
sem_post(&mutex); // Exit critical section
sem_post(&full); // Increase full count (indicates an item is available)
sleep(1); // Simulate time taken to produce
}
}
void* consumer(void* param) {
int item;
while (1) {
sem_wait(&full); // Decrease full count (check if buffer has items)
sem_wait(&mutex); // Enter critical section to access the buffer
item = buffer[out];
printf("Consumed: %d\n", item);
out = (out + 1) % MAX_BUFFER_SIZE;
sem_post(&mutex); // Exit critical section
sem_post(&empty); // Increase empty count (indicates space available in
the buffer)
sleep(1); // Simulate time taken to consume
}
}
int main() {
pthread_t prod, cons;
// Initialize semaphores
sem_init(&empty, 0, MAX_BUFFER_SIZE); // Initially, all buffer spaces are
empty
sem_init(&full, 0, 0); // Initially, no items are in the buffer
sem_init(&mutex, 0, 1); // Mutex to ensure mutual exclusion
// Create producer and consumer threads
pthread_create(&prod, NULL, producer, NULL);
pthread_create(&cons, NULL, consumer, NULL);
// Wait for threads to finish (This might never happen in an infinite loop)
pthread_join(prod, NULL);
pthread_join(cons, NULL);
// Destroy semaphores after usage
sem_destroy(&empty);
sem_destroy(&full);
sem_destroy(&mutex);
return 0;
}
OUTPUT:-