/* L-10 MCS 572 Wed 1 Feb 2012 : hello_pthreads.c
 * The simple program below illustrates the launching of a user given
 * number of threads.  Every thread writes hello world to screen,
 * using its thread identification number.  For the program to work
 * we must initialize the thread attribute and pass different addresses
 * as arguments to the function executed by each thread. */

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

void *say_hi ( void *args );
/* 
 * Every thread executes say_hi.
 * The argument contains the thread id. */

int main ( int argc, char* argv[] )
{
   printf("How many threads ? ");
   int n; scanf("%d",&n);
   {
      pthread_t t[n];
      pthread_attr_t a;
      int i,id[n];
      printf("creating %d threads ...\n",n);
      for(i=0; i<n; i++)
      {
         id[i] = i;
         pthread_attr_init(&a);
         pthread_create(&t[i],&a,say_hi,(void*)&id[i]);
      }
      printf("waiting for threads to return ...\n");
      for(i=0; i<n; i++) pthread_join(t[i],NULL);
   }
   return 0;
}

void *say_hi ( void *args )
{
   int *i = (int*) args;
   printf("hello world from thread %d!\n",*i);
   return NULL;
}

