/* Alert: link to the pthreads library by appending
   -lpthread to the compile statement */
#include <pthread.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h> /* for sleep */
#include <stdlib.h> /* for malloc */

#define NUM_THREADS 5

void *sleeping(void *);   /* thread routine */
pthread_t tid[NUM_THREADS];      /* array of thread IDs */

int main()
{
  int *sleeptime, i, retval;
  for ( i = 0; i < NUM_THREADS; i++) {
     sleeptime = (int *)malloc(sizeof(int));
     *sleeptime = (i+1)*2;
     retval =pthread_create(&tid[i], NULL, sleeping, 
             (void *)sleeptime);
     if (retval != 0) {
         perror("Error, could not create thread");
     }
  }
  for ( i = 0; i < NUM_THREADS; i++)
      pthread_join(tid[i], NULL);
  printf("main() reporting that all %d threads have terminated\n", i);
  return (0);
}  /* main */

void *sleeping(void *arg)
{
    int sleep_time = *(int *)arg;
    printf("thread %d sleeping %d seconds ...\n", 
           pthread_self(), sleep_time);
    sleep(sleep_time);
    printf("\nthread %d awakening\n", pthread_self());
    return (NULL);
}

