/* Testing of thread creation to find memory allocation bug
** This is coded to use as few extern functions as possible!
**
** The Sleep() should be long enough to enably WIN32 to create one thread
** that will be ended at once!
**
** The problem is that when this program is run it will allocate more and more
** memory, so there is a memory leak in the thread handling. The problem is how
** to avoid is !
**
** The problem is not that there is the sleep time is too short! The original
** program used conditions, but I removed this to make everything simpler!
*/

#include <windows.h>
#include <process.h>
#include <stdio.h>

#define TEST_COUNT 100000
#define SLEEP_TIME 100		/* wait 0.1 seconds for the thread to exit */

typedef HANDLE  pthread_t;
typedef void*	pthread_attr_t;

int pthread_create(pthread_t *thread_id, pthread_attr_t *attr,
		   unsigned (__stdcall *func)( void * ), void *param)
{
  HANDLE hThread;
  DWORD  id;
  hThread=(HANDLE)_beginthreadex(0,65536L,
				 func, param, CREATE_SUSPENDED, &id);
  if (!hThread)
  {
    errno=GetLastError();
    return errno ? errno : -1;
  }
  ResumeThread(hThread) ;
  *thread_id=hThread;
  return (0);
}

void pthread_exit(unsigned A)
{
   _endthreadex(A);
   if (!CloseHandle(GetCurrentThread()))
     printf("got error %d closing thread handler\n",GetLastError());
}

/* A real simple thread */

unsigned __stdcall test_thread(void *arg)
{
  pthread_exit(0);
  return 0;
}

int main(int argc,char **argv)
{
  pthread_t tid;
  pthread_attr_t thr_attr;
  int i,error;
  printf("Init ok. Creating %d threads\n",TEST_COUNT);

  for (i=1 ; i <= TEST_COUNT ; i++)
  {
    int *param= &i;
    if ((i % 100) == 0)
      printf("%8d",i);
    if ((error=pthread_create(&tid,&thr_attr,test_thread,(void*) param)))
    {
      fprintf(stderr,"\nGot error: %d from pthread_create (errno: %d)\n",
	      error,errno);
      exit(1);
    }
    Sleep(SLEEP_TIME);
  }
  printf("\nend\n");
  return 0;
}
