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

#include "mutex.h"
#include "semaphore.h"

typedef struct {
    semaphore_t empty;
    semaphore_t full;
    int mutex;
    int value;
} data_t;

static void *producer(void *data)
{
    data_t *d = data;

    while (1) {
        down(&d->empty);
        lock(&d->mutex);
        d->value++;
        usleep(100000);
        unlock(&d->mutex);
        up(&d->full);
    }

    return NULL;
}

static void *consumer(void *data)
{
    data_t *d = data;

    while (1) {
        down(&d->full);
        lock(&d->mutex);
        d->value--;
        usleep(100000);
        unlock(&d->mutex);
        up(&d->empty);
    }

    return NULL;
}

int main(int argc, char **argv)
{
    int i, n;
    pthread_t t;
    data_t *d;

    if (argc < 2) {
        fprintf(stderr, "Usage: %s <number of threads>\n", argv[0]);
        return 1;
    }
    n = atoi(argv[1]);

    d = malloc(n * sizeof(*d));
    for (i = 0; i < n; i++) {
        init(&d[i].empty, n);
        init(&d[i].full, 0);
        d[i].mutex = 0;
        d[i].value = 0;
        pthread_create(&t, NULL, producer, &d[i]);
        pthread_create(&t, NULL, consumer, &d[i]);
    }

    while (1) {
        for (i = 0; i < n; i++)
            printf("%2d ", d[i].value);
        printf("\n");
        usleep(500000);
    }

    return 0;
}
