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

#include "bench.h"

int argc;
char** argv;
volatile int go = 0;

pthread_cond_t c;
pthread_mutex_t m;

void __attribute__((noinline)) call() {
	pthread_mutex_lock(&m);
	pthread_cond_signal(&c);
	pthread_mutex_unlock(&m);
}

int  __attribute__((noinline)) wait() {
	pthread_mutex_lock(&m);
	go = 1;
	BENCH(
		for (size_t i = 0; i < n; i++) {
			pthread_cond_wait(&c, &m);
		},
		result
	)

	printf("%llu\n", result);
	go = 0;
	pthread_mutex_unlock(&m);
	return 0;
}

void* thread_main(void * a) {
	while(go == 0) { sched_yield(); }
	while(go == 1) { call(); }
	return NULL;
}

int main(int margc, char* margv[]) {
	argc = margc;
	argv = margv;
	pthread_t thread;
	if (pthread_create(&thread, NULL, thread_main, NULL) < 0) {
		perror( "failure" );
		return 1;
	}
	wait();
	if (pthread_join( thread, NULL) < 0) {
		perror( "failure" );
		return 1;
	}
	return 0;
}