#include <stdio.h>
#include <malloc.h>
#include <pthread.h>
#include <errno.h>
#include <stdlib.h>
#include <alloca.h>

#define TIMES		10000
#define TIMES_2		10000
#define TIMES_4		10000


/*static __thread int testtls;
 *  main.c:13: error: thread-local storage not supported for this target
 */

struct run_size {
	unsigned size;
	unsigned times;
}run[]={ {2, TIMES_2},
	{4, TIMES_4},
	{8, TIMES},
	{16, TIMES},
	{32, TIMES},
	{64, TIMES},
	{128, TIMES},
	{256, TIMES},
	{512, TIMES},
	{1024, TIMES},
	{2048, TIMES},
	{4096, TIMES},
	{8192, TIMES},
	{16384, TIMES},
	{32768, TIMES},
	{65536, TIMES},
	{131072, TIMES},
	{262144, TIMES},
	{524288, TIMES},
	{1048576, TIMES},
	{2097152, TIMES},
	};

void* test_default(void* arg) {

	int i, j;
	char*p;

	(void)arg;
	for(i=0; i<sizeof(run)/sizeof(struct run_size);i++) {
		for(j=0;j<run[i].times;j++)
		{
			p = malloc(run[i].size);
			free(p);
		}
	}
	return NULL;
}

int test(int times) {

	int i;

	for(i=0; i< times; i++) {
	
		
	}
	return 0;
}
		
int run_test_default_multi(int ts){

	pthread_t *tid;
	int i, ret;

	if (__stackavail() < ts*sizeof(pthread_t) )	
		tid = malloc(ts*sizeof(pthread_t));
	else
		tid = alloca(ts*sizeof(pthread_t));

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

		ret = pthread_create(&tid[i], NULL, test_default, NULL);
		if (ret !=EOK) {
			tid[i] = -1;
			printf("failed to create thread %i\n", i);
		}
	}


	for(i =0;i< ts; i++) {
		if (tid[i]!= -1) pthread_join(tid[i], NULL);
	}
	
	return 0;

}

int main(int argc, char** argv) {

	int ts;
	if (argc == 1)
		test_default(NULL);
	else {
		ts = atoi(argv[1]);
		if (ts <=0)
			test_default(NULL);
		else
			run_test_default_multi(ts);
	}
	
	return 0;
}
