Semaphores Producer Consumer
Semaphores Producer Consumer
h>
#include <pthread.h>
#include <semaphore.h>
#define BUFFER_SIZE 5
int buffer[BUFFER_SIZE];
int in = 0, out = 0;
sem_init(&mutex, 0, 1);
sem_init(&empty, 0, BUFFER_SIZE);
sem_init(&full, 0, 0);
// Create producer and consumer threads
pthread_create(&tid_producer, NULL, producer, NULL);
pthread_create(&tid_consumer, NULL, consumer, NULL);
// Wait for threads to finish
pthread_join(tid_producer, NULL);
pthread_join(tid_consumer, NULL);
// Destroy semaphores
sem_destroy(&mutex);
sem_destroy(&empty);
sem_destroy(&full);
return 0;
}