#include   <stdio.
h>
#include   <pthread.h>
#include   <semaphore.h>
#include   <unistd.h>
#define N 5 // Buffer size
sem_t mutex, empty, full;
int buffer[N];
int in = 0, out = 0;
void* producer(void* arg) {
    for (int i = 0; i < 10; i++) {
        sem_wait(&empty);
        sem_wait(&mutex);
        buffer[in] = i;
        printf("Produced: %d\n", buffer[in]);
        in = (in + 1) % N;
        sem_post(&mutex);
        sem_post(&full);
        sleep(1);
    }
    return NULL;
}
void* consumer(void* arg) {
    for (int i = 0; i < 10; i++) {
        sem_wait(&full);
        sem_wait(&mutex);
        int item = buffer[out];
        printf("Consumed: %d\n", item);
        out = (out + 1) % N;
        sem_post(&mutex);
        sem_post(&empty);
        sleep(1);
    }
    return NULL;
}
int main() {
    pthread_t p, c;
    sem_init(&mutex, 0, 1);
    sem_init(&empty, 0, N);
    sem_init(&full, 0, 0);
    pthread_create(&p, NULL, producer, NULL);
    pthread_create(&c, NULL, consumer, NULL);
    pthread_join(p, NULL);
    pthread_join(c, NULL);
    sem_destroy(&mutex);
    sem_destroy(&empty);
    sem_destroy(&full);
    return 0;
}