#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);
	}
}

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

void* thread1(void* arg) {
	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) );
	}
}

void* thread2(void* arg) {
	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) );
	}
}

int main(int argc, char *argv[]) {
	pthread_t t1, t2;

	check( pthread_create(&t1, NULL, thread1, NULL) );
	check( pthread_create(&t2, NULL, thread2, NULL) );

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

	return EXIT_SUCCESS;
}

