Thread Termination

Terminating Threads. There are several ways in which a Pthread may be terminated:
a The thread returns from its starting routine (the main routine for the initial thread).
b The thread makes a call to the pthread_exit subroutine.
c The thread is cancelled by another thread via the pthread_cancel routine.
d The entire process is terminated due to a call to either the exec or exit subroutines.
  • If main finishes before the threads and exits with pthread_exit(), the other threads will continue to execute (join function!).
  • If main finishes after the threads and exits, the threads will be automatically terminated.
Example Code:
    1 #include <pthread.h>
    2 #include <stdio.h>
    3 #include <stdlib.h>
    4 #include <unistd.h>
    5 
    6 #define NUM_THREADS	5
    7 
    8 void *PrintHello(void *threadid)
    9 {
   10    sleep(10);
   11    long tid;
   12    tid = (long)threadid;
   13    printf("Hello World! It's me, thread #%ld!\n", tid);
   14    pthread_exit(NULL);
   15 }
   16 
   17 int main(int argc, char *argv[])
   18 {
   19    pthread_t threads[NUM_THREADS];
   20    int rc;
   21    long t;
   22    for(t=0;t<NUM_THREADS;t++){
   23      printf("In main: creating thread %ld\n", t);
   24      rc = pthread_create(&threads[t], NULL, PrintHello, (void *)t);
   25      if (rc){
   26        printf("ERROR; return code from pthread_create() is %d\n", rc);
   27        exit(-1);
   28        }
   29      }
   30 
   31    /* Last thing that main() should do */
   32    pthread_exit(NULL);
   33 }