### Terminating a Thread

A thread exists until it terminates and the pthread_detach( ) routine is called for the thread. The pthread_detach( ) routine can be called for a thread before or after it terminates. If the thread terminates before pthread_detach( ) is called for it, then the thread continues to exist and can be synchronized (joined) until it is detached. Thus, the object (thread) can be detached by any thread that has access to a handle to the object.

Note that pthread_detach( ) must be called to release the memory allocated for the thread objects so that this storage does not build up and cause the process to run out of memory. For example, after a thread returns from a call to join, it detaches the joined-to thread if no other threads join with it. Similarly, if a thread has no other threads joining with it, it detaches itself so that its thread object is deallocated as soon as it terminates.

A thread terminates for any of the following reasons:

· The thread returns from its start routine; this is the usual case.

· The thread calls the pthread_exit( ) routine.

The pthread_exit( ) routine terminates the calling thread and returns a status value, indicating the thread's exit status to any potential joiners.

· The thread is canceled by a call to the pthread_cancel( ) routine.

The pthread_cancel( ) routine requests termination of a specified thread if cancellation is permitted. (See Thread Cancellation for more information on canceling threads and controlling whether or not cancellation is permitted.)

· An error occurs in the thread.

Examples of errors that cause thread termination are programming errors, segmentation faults, or unhandled exceptions.

###