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

void check(int error) {
    if (error != 0) {
        fprintf(stderr, "Error: %s\n", strerror(error));
        exit(EXIT_FAILURE);
    }
}

volatile int ei_teller = 0;
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t c = PTHREAD_COND_INITIALIZER;

void* consumer(void* par) {
    while (1) {
        check( pthread_mutex_lock(&m) );
        while (ei_teller < 12)
            check( pthread_cond_wait(&c, &m) );
        ei_teller -= 12;
        printf("teller is verlaagd en is nu %d\n", ei_teller);
        check( pthread_mutex_unlock(&m) );
    }
    return NULL;
}

void* producer(void* par) {
    int n;
    printf("Geef waarden voor n: ");
    while (1) {
        scanf("%d", &n);
        check( pthread_mutex_lock(&m) );
        ei_teller += n;
        check( pthread_cond_signal(&c) );
        check( pthread_mutex_unlock(&m) );
    }
    return NULL;
}

int main(void) {
    pthread_t t1, t2;

    check( pthread_create(&t1, NULL, &consumer, NULL) );
    check( pthread_create(&t2, NULL, &producer, NULL) );

    check( pthread_join(t1, NULL) );
    check( pthread_join(t2, NULL) );

    return EXIT_SUCCESS;
}

