#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <time.h>
#include <errno.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) {
		struct timespec ts;
		int r=0;
		check( pthread_mutex_lock(&m) );
		clock_gettime(CLOCK_REALTIME, &ts);
		ts.tv_sec+=5; 
		while (ei_teller<12 && r==0)
			r=pthread_cond_timedwait(&c, &m, &ts);
		if (r!=0) {
			if (r==ETIMEDOUT)
				printf("Schiet eens op!\n");
			else
				fprintf(stderr, "Error: %s\n", strerror(r));
		}
		else {
			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=0;
	printf("Geef waarden voor n (negatief om te stoppen): ");
	while (n>=0) {
		scanf("%d", &n);
		if (n>=0) {
			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(t2, NULL) );

	return EXIT_SUCCESS;
}
