/* Asanga Udugama (adu@comnets.uni-bremen.de)*/

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

// gcc -lpthread  -o thread_test thread_test.c

pthread_mutex_t  mut;
pthread_t  tid1, tid2;

int count1, count2;


int work_func(int code)
{
	printf("%d doing work \n", code);
	sleep(1);
	printf("%d work done \n", code);
}

void *func(void *param)
{
	int code = *((int *) param);

	while(1) {
		if(code == 1) {
			count1++;
			printf("%d is going to sleep for 1sec (count1=%d)\n", code, count1);
			sleep(1);
			printf("%d is comming out of sleep \n", code);
		} else {
			count2++;
			printf("%d is going to sleep for 1sec (count2=%d)\n", code, count2);
			sleep(1);
			printf("%d is comming out of sleep \n", code);
		}
		pthread_mutex_lock(&mut);
		printf("%d got lock \n", code);
		work_func(code);
		printf("%d let lock \n", code);
		pthread_mutex_unlock(&mut);

	}
}

int main(int argc, char *argv[])
{
	int code;

	pthread_mutex_init(&mut, NULL);

	count1 = 0;
	count2 = 0;

	code = 1;
	pthread_create(&tid1, NULL, func, (void *) &code );
	sleep(1);
	code = 2;
	pthread_create(&tid2, NULL, func, (void *) &code );

	pthread_join(tid1, NULL);
	pthread_join(tid2, NULL);
	
}
