#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#include <stdbool.h>

#define n 5 // Μέγεθος buffer

int b[n];
int in = 0;
int out = 0;

void* producer(void* arg) {
    int v = 0;
    while (true) {
        /* produce item v */
        while ((in + 1) % n == out) /* busy wait αν είναι γεμάτος */;
        
        b[in] = v;
        printf("Produced to buffer[%d]: %d\n", in, v);
        v++;
        in = (in + 1) % n;
        usleep(200000);
    }
    return NULL;
}

void* consumer(void* arg) {
    int w;
    while (true) {
        while (in == out) /* busy wait αν είναι άδειος */;
        
        w = b[out];
        printf("Consumed from buffer[%d]: %d\n", out, w);
        out = (out + 1) % n;
        usleep(400000);
    }
    return NULL;
}

int main() {
    pthread_t prod, cons;
    pthread_create(&prod, NULL, producer, NULL);
    pthread_create(&cons, NULL, consumer, NULL);
    pthread_join(prod, NULL);
    pthread_join(cons, NULL);
    return 0;
}
