Lab00: Hello Threads

Objective
To run a Pthread program. Topics include printf, pthread_t, pthread_create(), pthread_exit()

Background
  1. To compile your Pthread program:
    gcc -o helloThread helloThread.c -lpthread, where "-lpthread" links the pthread library
  2. An important function is: pthread_create (thread,attr,start_routine,arg)
Assignment
Create a file named helloThread.c that contains the program shown below. Run the program using the compile line given above.

helloThread.c
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5

void *PrintHello(void *threadid)
{
   printf("\n%d: Hello World!\n", threadid);
   pthread_exit(NULL);
}

int main (int argc, char *argv[])
{
   pthread_t threads[NUM_THREADS];
   int rc, t;
   for(t=0;t < NUM_THREADS;t++){
       rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
        if (rc){
            printf("ERROR; return code from pthread_create() is %d\n", rc);
            exit(-1);
        }
    }
    pthread_exit(NULL);
}

Sample Output (Run the program several times, the output should vary)
Creating thread 0

0: Hello World!
Creating thread 1

1: Hello World!
Creating thread 2
Creating thread 3
Creating thread 4

2: Hello World!

3: Hello World!

4: Hello World!