#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>

#define TRUE 1
#define FALSE 0
#define N 2

int interested[N];
int turn = 0;
int out = 0;
int last = -1;

void enter_region(int process) {
	int other = 1 - process;
	interested[process] = TRUE;
	turn = process;
	while ((interested[other] == TRUE) && (turn == process));
}

void leave_region(int process) {
	interested[process] = FALSE;
}

void P1(void *data) {
	while (TRUE) {
		//sleep(10);

		enter_region(0);
		if (last != out) {
			printf("out = %d\n", out);
			last++;
		}
		leave_region(0);		
	}
}

void P2(void *data) {
	while (TRUE) {
		enter_region(1);
		out++;
		leave_region(1);
	}
}

int main (int argc, const char * argv[]) {
	pthread_t p1, p2;
	pthread_create(&p1, NULL, P1, NULL);
	pthread_create(&p2, NULL, P2, NULL);
	
	pthread_join(p1, NULL);
	pthread_join(p2, NULL);
	
    exit(0);
}

