#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 teller;
pthread_mutex_t tm = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t tc = PTHREAD_COND_INITIALIZER;

void* thread1(void* arg) {
	while (1) {
		check( pthread_mutex_lock(&tm) );
		while (teller<10)
			check( pthread_cond_wait(&tc, &tm) );
		teller-=10;
		printf("teller is verlaagd en is nu %d\n", teller);
		check( pthread_mutex_unlock(&tm) );
	}
}

void* thread2(void* arg) {
	int n;
	printf("Geef waarden voor n: ");
	while (1) {
		scanf("%d", &n);
		check( pthread_mutex_lock(&tm) );
		teller+=n;
		check( pthread_cond_signal(&tc) );
		check( pthread_mutex_unlock(&tm) );
	}
}

int main(int argc, char *argv[]) {
	pthread_t p1, p2;

	check( pthread_create(&p1, NULL, thread1, NULL) );
	check( pthread_create(&p2, NULL, thread2, NULL) );

	check( pthread_join(p1, NULL) );
	check( pthread_join(p2, NULL) );

	return EXIT_SUCCESS;
}

