#include <rtl.h>
#include <time.h>
#include <pthread.h>

#define NTHREAD 5
#define THREAD_STACK_SIZE 20000

static pthread_t thread;

static char preallocated [NTHREAD][THREAD_STACK_SIZE];
static pthread_t threads [NTHREAD];

void * start_routine(void *param)
{
	int arg = (int) param;
	int newthread = arg - 1;
	int ret;
	pthread_attr_t attr;

	rtl_printf("Thread %d is running\n", arg);
	if (!arg) {
		return 0;
	}

	rtl_printf("Thread %d creating thread %d\n", arg, newthread);

	pthread_attr_init (&attr);
	pthread_attr_setstackaddr (&attr, preallocated [newthread]);
	pthread_attr_setstacksize (&attr, THREAD_STACK_SIZE);

	ret = pthread_create (&threads [newthread], &attr, start_routine, (void *) (newthread));
	if (ret) {
		rtl_printf("failed to create thread %d\n", newthread);
	}
	return 0;
}

int init_module(void) {
	return pthread_create (&thread, NULL, start_routine, (void *) NTHREAD);
}

void cleanup_module(void) {
	int i;
	pthread_cancel (thread);
	pthread_join (thread, NULL);
	for (i = 0; i < NTHREAD; i ++) {
		if (threads[i]) {
			pthread_cancel (threads[i]);
			pthread_join(threads[i], NULL);
		}
	}
}
