/*
 * POSIX.1 Signals
 *
 * Written by J. Vidal
 * Copyright (C) Dec, 2002 OCERA Consortium.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2.
 *
 *  Simple program showing stack overflow when sending RTL_SIGNAL_SUSPEND 
 *  signal. J. Vidal (OCERA)
 *
 */

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

#define NTASKS 2
#define MAXINT 0x7fffffff
pthread_t thread[NTASKS];

void * start_routine(void *arg)
{
	struct sched_param p;
	int ret=0,i=0,param=(unsigned) arg;
	long long period=10*1000*1000;

	p . sched_priority = NTASKS -param;
	pthread_setschedparam (pthread_self(), SCHED_FIFO, &p);

	if (param==0){
	  pthread_make_periodic_np (pthread_self(), gethrtime(),period );
	  
	  while (i++<MAXINT) {
	    pthread_wait_np ();
	    pthread_suspend_np(thread[1]);
	    // Test that thread 1 is alive.
	    ret=pthread_kill(thread[1],0);
	    if (ret==ESRCH){
	      rtl_printf("STACK EXHAUSTED in iter:%d\n",i);
              pthread_suspend_np(pthread_self());
}
	    else
	      rtl_printf("iter:%d\n",i);
	  }
	}else {
	  pthread_make_periodic_np (pthread_self(), gethrtime(),period*2);
	  while (1){
	    pthread_wait_np();
	  }
	  
	  for (i=1;i<500;i++)
	    rtl_printf("thread %d without control\n",param);
	  pthread_suspend_np(thread[0]);
	}
	
	return 0;
}

int init_module(void) {
  int i,err=0;
  for (i=0;i<NTASKS;i++)
    err=pthread_create (&thread[i], NULL, start_routine, (int *) i);
  
  return err;
}

void cleanup_module(void) {
  int i;
  for (i=0;i<NTASKS;i++)
    pthread_delete_np (thread[i]);
}
