#include <stdio.
h>
#include <stdlib.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#define BUFFER_SIZE 5 // Size of the shared buffer
int buffer[BUFFER_SIZE];
int in = 0, out = 0; // Indices for producer and consumer
sem_t empty; // Semaphore to track empty slots
sem_t full; // Semaphore to track filled slots
pthread_mutex_t mutex; // Mutex to protect critical section
void *producer(void *arg) {
for (int i = 1; i <= 10; i++) { // Produce 10 items
sem_wait(&empty); // Wait if no empty slot is available
pthread_mutex_lock(&mutex); // Lock the critical section
// Produce an item
buffer[in] = i;
printf("Produced: %d\n", i);
in = (in + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex); // Unlock the critical section
sem_post(&full); // Signal that a slot is filled
sleep(1); // Simulate production time
}
return NULL;
}
void *consumer(void *arg) {
for (int i = 1; i <= 10; i++) { // Consume 10 items
sem_wait(&full); // Wait if no filled slot is available
pthread_mutex_lock(&mutex); // Lock the critical section
// Consume an item
int item = buffer[out];
printf("Consumed: %d\n", item);
out = (out + 1) % BUFFER_SIZE;
pthread_mutex_unlock(&mutex); // Unlock the critical section
sem_post(&empty); // Signal that a slot is empty
sleep(2); // Simulate consumption time
}
return NULL;
}
int main() {
pthread_t producer_thread, consumer_thread;
// Initialize semaphores and mutex
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
pthread_mutex_init(&mutex, NULL);
// Create producer and consumer threads
pthread_create(&producer_thread, NULL, producer, NULL);
pthread_create(&consumer_thread, NULL, consumer, NULL);
// Wait for threads to complete
pthread_join(producer_thread, NULL);
pthread_join(consumer_thread, NULL);
// Clean up
sem_destroy(&empty);
sem_destroy(&full);
pthread_mutex_destroy(&mutex);
printf("Producer-Consumer process completed!\n");
return 0;
}