/*
 * --  thread.c.3
 *     Test of async context switching.
 */
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include "utils.h"

#define ITERATIONS (1000000)
#define THREADS (1)

static void 
proc( struct timeval *tv )
{
   long i, sum = 0;
   
   for(i = 0; i < ITERATIONS; i++)
       sum += 1;

   i = 0;
   while( --sum >= 0 )
       i += 1;

   pthread_exit( (void *) SUCCESS );
}

static pthread_t  *th;
static pthread_attr_t attr;
   
int 
main( int argc, char *argv[] )
{
   int thread_count = THREADS, i, exit_status;
   struct sched_param param = { SCHED_ROUND_ROBIN_C,
                                PRI_RR_DEFAULT,
                                1                    /* A single quantum */
                              };

   if( argc == 2 )
       thread_count = atoi( argv[1] );

   (void) pthread_attr_init( &attr );
   (void) pthread_attr_setdetachstate( &attr, PTHREAD_CREATE_JOINABLE );
   (void) pthread_attr_setschedparam( &attr, &param );

   (void) pthread_setprio_np( pthread_self(), PRI_RR_MAX );
   th = malloc( thread_count * sizeof( pthread_t * ) );

   for(i = 0; i < thread_count; i++ )
       (void) pthread_create( &th[i], &attr, (thread_proc_t) proc, NULL );

   for(i = 0; i < thread_count; i++ )
   {
       (void) pthread_join( th[i], (void **) &exit_status );
       if( exit_status != SUCCESS )
           fprintf(stderr, "Failed to join with th[%d]!\n", i);
   }

   free( th );
   (void) pthread_attr_destroy( &attr );

   print_system_counters();
   return( EXIT_SUCCESS );
}
