#include <stdio.h>	/* standard C i/o facilities */
#include <unistd.h>	/* Unix System Calls */
#include <sys/types.h>	/* system data type definitions */
#include <stdlib.h>	/* malloc */
#include <pthread.h>	/* Posix Threads stuff */
#include <errno.h>

/* Here is the function that will be called by pthread_create,
   this is what each new thread will be running
   For this example we are not passing any useful
   value to the thread.
 */

void *threadfunc( void *arg) {
  printf("I am thread # %d\n",(int)pthread_self());
  return(NULL);
}

int main(int argc, char **argv) {
  int i,num;
  int rval;
  pthread_t pt;

  if (argc<2) {
    printf("Tell me how many threads to create!\n");
    exit(1);
  }

  num = atoi(argv[1]);
  if ((num<=0) || (num>10)) {
    printf("Invalid number of threads - try again\n");
    exit(1);
  }

  for (i=0;i<num;i++) {
    printf("Starting thread %d\n",i);
    if ((rval=pthread_create(&pt,NULL,threadfunc,NULL))!=0) {
      printf("Error starting thread %d\n",rval);
    }
    if (pthread_join(pt,NULL)!=0) {
      printf("Error waiting for thread to finish\n");
    }
    printf("Done starting thread %d\n",i);
  }

  return(0);
}

