/*
 * --  thread.c.2
 *     Test of pthread_delay_np() and friends
 */
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include "utils.h"

#define ITERATIONS (100)

static void 
proc( struct timespec *tv )
{
   long sum = 0;
   int i, st;

   for(i = 0; i < ITERATIONS; i++ )
       sum += 1;
   
   st = pthread_delay_np( tv );
   CHECK(st, "pthread_delay_np()");

   for(i = 0; i < ITERATIONS; i++ )
       sum += 1;

   pthread_exit( (void *) SUCCESS );
}

static pthread_t  *th;

int 
main( int argc, char *argv[] )
{
   int i, st, exit_status, num_threads = 1;
   struct timespec tv;

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

   th = malloc_r( num_threads * sizeof( pthread_t ));

   tv.tv_sec = 10;
   tv.tv_nsec = rand() % 500000 + 100000;

   for(i = 0; i < num_threads; i++ )
   {
       st = create_joinable( &th[i], (thread_proc_t) proc, &tv );
	   CHECK(st, "create_joinable()");
   }

   for(i = 0; i < num_threads; i++ )
   {
       st = pthread_join( th[i], (void **) &exit_status );
	   CHECK(st, "pthread_join()");

	   pthread_lock_global_np();
       if( exit_status != SUCCESS )
           fprintf(stderr, "Failed to join with thread[%d]!\n", i + 2 );
	   else
		   printf("Joined with thread[%d]!\n", i + 2 );
	   pthread_unlock_global_np();
   }

   free_r( th );

   print_system_counters();
   return( EXIT_SUCCESS );
}

