Exiting a Thread
The pthread_exit library call terminates a thread in much the same manner as a call to exit terminates a process. The pthread_exit library call is shown in Table 11.2.
The pthread_exit library call takes a single argument, a reference to a retval value. This reference is returned when a nondetached thread is exited. Upon termination, the thread releases its thread-specific (but not process-specific) resources. If the thread was nondetached, its status information and thread ID are kept by the system until a join is issued or the creating process terminates. When the function being executed by the thread performs a return (implicitly or explicitly), the system implicitly calls pthread_exit .
Table 11.2. The pthread_exit Library Function
Include File(s) |
Manual Section |
3 |
||
Summary |
void pthread_exit (void * retval); |
|||
Return |
Success |
Failure |
Sets errno |
|
This call does not return |
In Chapter 3, Section 5, "Ending a Process," the atexit library function was presented. This function allows the user to specify one or more user -defined functions to be called in a LIFO (last-in, first-out) manner when the process exits. In asimilar vein there is a small suite of pthread cleanup calls that can be usedto specify and manipulate user-defined functions that are called when athread exits. In this grouping are the calls pthread_cleanup_pop , whichremoves a function from the cancellation cleanup stack, and thread_cleanup_push , which pushes a function on the cancellation stack of the current thread. Additionally, nonportable versions of these functions (called pthread_cleanup_pop_restore_np and pthread_cleanup_push_defer_np ) are provided. A full discussion of these functions is beyond the scope of this text.