
/*
	This is the Linux version of multi_thread
	The program demonstrates the use of threads and mutexex in Linux.
	We use the pthread library and must compile the program with -lpthread.
*/

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

#define MAX_THREADS 32

typedef struct {
	int thread_num;
} thread_data;

void* PrintFunc(void*);

pthread_mutex_t print_mutex = PTHREAD_MUTEX_INITIALIZER;

int thread_num = 0;

pthread_t pids[MAX_THREADS]; 
thread_data pdata[MAX_THREADS];

int main() {
	int i;

	thread_num = 5;

	for(i = 0; i < thread_num; ++i) {

		/* this line might not work
		pthread_create(&pids[i], NULL, &PrintFunc, &i);
			because i might change until the thread starts to run */

		/* this line might not work
		pthread_create(&pids[i], NULL, &PrintFunc, &pids[i]);
			because pids[i] might not be initialized before the thread
			starts to tun */

		pdata[i].thread_num = i;
		pthread_create(&pids[i], NULL, &PrintFunc, &pdata[i]);
	}

	for(i = 0; i < thread_num; ++i)
		pthread_join(pids[i], NULL);

	pthread_mutex_destroy(&print_mutex);

	return 0;
}

void* PrintFunc(void* data) {
	int i, j;
	int my_thread_num = ((thread_data *)data)->thread_num;
	
	for (i = 0; i < 5; ++i) {
		
		pthread_mutex_lock(&print_mutex);

		for (j = 0; j < 40; ++j)
			printf("%d", my_thread_num);
		printf("\n");

		pthread_mutex_unlock(&print_mutex);

	}

	return NULL;
}


