#define _REENTRANT

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/time.h>
#include <pthread.h>

static volatile int _must_stop = 0;

static void *thread_routine(void *arg)
{
	char *ptr = (char *)arg;
	
	errno = (int)ptr;
	while (!_must_stop)
	{
		printf("from thread %d! errno is %d right now...\n", ptr, errno);
		sleep(1);
	}
}


int main()
{
	pthread_t id_thread;

	pthread_create(&id_thread, NULL, thread_routine, (void *)1);
	pthread_create(&id_thread, NULL, thread_routine, (void *)2);
	pthread_create(&id_thread, NULL, thread_routine, (void *)3);

	errno = 5;

	pthread_create(&id_thread, NULL, thread_routine, (void *)4);

	sleep(2);
	// Guarantee that fourth thread started before setting errno by sleeping 2 seconds
	
	/* 
	 * BY COMMENTING THE ASSIGNMENT BELOW, THE PRINTF(NOK) WILL BE SHOWN 
	 * WHEN USING mipsel-linux-gcc uCLibc-0.9.28 BUT NOT USING SuSE 10 gcc and glibc-2.3.5
	 */
	//errno = 5;

	while (1)
	{
		printf("from main! errno is %d right now...\n", errno);
		sleep(1);
		if (errno != 5)
			printf("NOK - errno should be thread local(== 5), but its value is %d\n", errno);
	}

	return EXIT_SUCCESS;
}

