- $$
- 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.
- Typically, the pthread_exit routine is called after a thread has completed its work and is no longer required to exist.
- 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.
- $$
- Cleanup: the pthread_exit() routine does not close files; any files opened inside the thread will remain open after the thread is terminated.
- Example: This example code creates 5 threads with the pthread_create() routine.
- Each thread prints a 'Hello World!' message, and then terminates with a call to pthread_exit().
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
void *PrintHello(void *threadid)
{
long tid;
tid = (long)threadid;
printf("Hello World! It's me, thread #%ld!\n", tid);
pthread_exit(NULL);
}
int main (int argc, char *argv[])
{
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t=0; t<NUM_THREADS; t++){
printf("In main: creating thread %ld\n", 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);
}
Cem Ozdogan
2010-11-21