Section 11.5. Thread Termination

team bbl


11.5. Thread Termination

If any thread within a process calls exit, _Exit, or _exit, then the entire process terminates. Similarly, when the default action is to terminate the process, a signal sent to a thread will terminate the entire process (we'll talk more about the interactions between signals and threads in Section 12.8).

A single thread can exit in three ways, thereby stopping its flow of control, without terminating the entire process.

  1. The thread can simply return from the start routine. The return value is the thread's exit code.

  2. The thread can be canceled by another thread in the same process.

  3. The thread can call pthread_exit.

 #include <pthread.h> void pthread_exit(void *rval_ptr); 


The rval_ptr is a typeless pointer, similar to the single argument passed to the start routine. This pointer is available to other threads in the process by calling the pthread_join function.

 #include <pthread.h> int pthread_join(pthread_t thread, void **rval_ptr); 

Returns: 0 if OK, error number on failure


The calling thread will block until the specified thread calls pthread_exit, returns from its start routine, or is canceled. If the thread simply returned from its start routine, rval_ptr will contain the return code. If the thread was canceled, the memory location specified by rval_ptr is set to PTHREAD_CANCELED.

By calling pthread_join, we automatically place a thread in the detached state (discussed shortly) so that its resources can be recovered. If the thread was already in the detached state, calling pthread_join fails, returning EINVAL.

If we're not interested in a thread's return value, we can set rval_ptr to NULL. In this case, calling pthread_join allows us to wait for the specified thread, but does not retrieve the thread's termination status.

Example

Figure 11.3 shows how to fetch the exit code from a thread that has terminated.

Running the program in Figure 11.3 gives us

     $ ./a.out     thread 1 returning     thread 2 exiting     thread 1 exit code 1     thread 2 exit code 2 

As we can see, when a thread exits by calling pthread_exit or by simply returning from the start routine, the exit status can be obtained by another thread by calling pthread_join.

Figure 11.3. Fetching the thread exit status
 #include "apue.h" #include <pthread.h> void * thr_fn1(void *arg) {     printf("thread 1 returning\n");     return((void *)1); } void * thr_fn2(void *arg) {     printf("thread 2 exiting\n");     pthread_exit((void *)2); } int main(void) {     int         err;     pthread_t   tid1, tid2;     void        *tret;     err = pthread_create(&tid1, NULL, thr_fn1, NULL);     if (err != 0)         err_quit("can't create thread 1: %s\n", strerror(err));     err = pthread_create(&tid2, NULL, thr_fn2, NULL);     if (err != 0)         err_quit("can't create thread 2: %s\n", strerror(err));     err = pthread_join(tid1, &tret);     if (err != 0)         err_quit("can't join with thread 1: %s\n", strerror(err));     printf("thread 1 exit code %d\n", (int)tret);     err = pthread_join(tid2, &tret);     if (err != 0)         err_quit("can't join with thread 2: %s\n", strerror(err));     printf("thread 2 exit code %d\n", (int)tret);     exit(0); } 

The typeless pointer passed to pthread_create and pthread_exit can be used to pass more than a single value. The pointer can be used to pass the address of a structure containing more complex information. Be careful that the memory used for the structure is still valid when the caller has completed. If the structure was allocated on the caller's stack, for example, the memory contents might have changed by the time the structure is used. For example, if a thread allocates a structure on its stack and passes a pointer to this structure to pthread_exit, then the stack might be destroyed and its memory reused for something else by the time the caller of pthread_join tries to use it.

Example

The program in Figure 11.4 shows the problem with using an automatic variable (allocated on the stack) as the argument to pthread_exit.

When we run this program on Linux, we get

    $ ./a.out    thread 1:      structure at 0x409a2abc      foo.a = 1      foo.b = 2      foo.c = 3      foo.d = 4    parent starting second thread    thread 2: ID is 32770    parent:      structure at 0x409a2abc      foo.a = 0      foo.b = 32770      foo.c = 1075430560      foo.d = 1073937284 

Of course, the results vary, depending on the memory architecture, the compiler, and the implementation of the threads library. The results on FreeBSD are similar:

    $ ./a.out    thread 1:      structure at 0xbfafefc0      foo.a = 1      foo.b = 2      foo.c = 3      foo.d = 4    parent starting second thread    thread 2: ID is 134534144    parent:      structure at 0xbfafefc0      foo.a = 0      foo.b = 134534144      foo.c = 3      foo.d = 671642590 

As we can see, the contents of the structure (allocated on the stack of thread tid1) have changed by the time the main thread can access the structure. Note how the stack of the second thread (tid2) has overwritten the first thread's stack. To solve this problem, we can either use a global structure or allocate the structure using malloc.

Figure 11.4. Incorrect use of pthread_exit argument
 #include "apue.h" #include <pthread.h> struct foo {     int a, b, c, d; }; void printfoo(const char *s, const struct foo *fp) {     printf(s);     printf("  structure at 0x%x\n", (unsigned)fp);     printf("  foo.a = %d\n", fp->a);     printf("  foo.b = %d\n", fp->b);     printf("  foo.c = %d\n", fp->c);     printf("  foo.d = %d\n", fp->d); } void * thr_fn1(void *arg) {     struct foo  foo = {1, 2, 3, 4};     printfoo("thread 1:\n", &foo);     pthread_exit((void *)&foo); } void * thr_fn2(void *arg) {     printf("thread 2: ID is %d\n", pthread_self());     pthread_exit((void *)0); } int main(void) {     int         err;     pthread_t   tid1, tid2;     struct foo  *fp;     err = pthread_create(&tid1, NULL, thr_fn1, NULL);     if (err != 0)         err_quit("can't create thread 1: %s\n", strerror(err));     err = pthread_join(tid1, (void *)&fp);     if (err != 0)         err_quit("can't join with thread 1: %s\n", strerror(err));     sleep(1);     printf("parent starting second thread\n");     err = pthread_create(&tid2, NULL, thr_fn2, NULL);     if (err != 0)         err_quit("can't create thread 2: %s\n", strerror(err));     sleep(1);     printfoo("parent:\n", fp);     exit(0); } 

One thread can request that another in the same process be canceled by calling the pthread_cancel function.

 #include <pthread.h> int pthread_cancel(pthread_t tid); 

Returns: 0 if OK, error number on failure


In the default circumstances, pthread_cancel will cause the thread specified by tid to behave as if it had called pthread_exit with an argument of PTHREAD_CANCELED. However, a thread can elect to ignore or otherwise control how it is canceled. We will discuss this in detail in Section 12.7. Note that pthread_cancel doesn't wait for the thread to terminate. It merely makes the request.

A thread can arrange for functions to be called when it exits, similar to the way that the atexit function (Section 7.3) can be used by a process to arrange that functions can be called when the process exits. The functions are known as thread cleanup handlers. More than one cleanup handler can be established for a thread. The handlers are recorded in a stack, which means that they are executed in the reverse order from that with which they were registered.

[View full width]

 #include <pthread.h> void pthread_cleanup_push(void (*rtn)(void *),  void *arg); void pthread_cleanup_pop(int execute); 


The pthread_cleanup_push function schedules the cleanup function, rtn, to be called with the single argument, arg, when the thread performs one of the following actions:

  • Makes a call to pthread_exit

  • Responds to a cancellation request

  • Makes a call to pthread_cleanup_pop with a nonzero execute argument

If the execute argument is set to zero, the cleanup function is not called. In either case, pthread_cleanup_pop removes the cleanup handler established by the last call to pthread_cleanup_push.

A restriction with these functions is that, because they can be implemented as macros, they must be used in matched pairs within the same scope in a thread. The macro definition of pthread_cleanup_push can include a { character, in which case the matching } character is in the pthread_cleanup_pop definition.

Example

Figure 11.5 shows how to use thread cleanup handlers. Although the example is somewhat contrived, it illustrates the mechanics involved. Note that although we never intend to pass a nonzero argument to the thread start-up routines, we still need to match calls to pthread_cleanup_pop with the calls to pthread_cleanup_push; otherwise, the program might not compile.

Running the program in Figure 11.5 gives us

     $ ./a.out     thread 1 start     thread 1 push complete     thread 2 start     thread 2 push complete     cleanup: thread 2 second handler     cleanup: thread 2 first handler     thread 1 exit code 1     thread 2 exit code 2 

From the output, we can see that both threads start properly and exit, but that only the second thread's cleanup handlers are called. Thus, if the thread terminates by returning from its start routine, its cleanup handlers are not called. Also note that the cleanup handlers are called in the reverse order from which they were installed.

Figure 11.5. Thread cleanup handler
 #include "apue.h" #include <pthread.h> void cleanup(void *arg) {     printf("cleanup: %s\n", (char *)arg); } void * thr_fn1(void *arg) {     printf("thread 1 start\n");     pthread_cleanup_push(cleanup, "thread 1 first handler");     pthread_cleanup_push(cleanup, "thread 1 second handler");     printf("thread 1 push complete\n");     if (arg)         return((void *)1);     pthread_cleanup_pop(0);     pthread_cleanup_pop(0);     return((void *)1); } void * thr_fn2(void *arg) {     printf("thread 2 start\n");     pthread_cleanup_push(cleanup, "thread 2 first handler");     pthread_cleanup_push(cleanup, "thread 2 second handler");     printf("thread 2 push complete\n");     if (arg)         pthread_exit((void *)2);     pthread_cleanup_pop(0);     pthread_cleanup_pop(0);     pthread_exit((void *)2); } int main(void) {     int         err;     pthread_t   tid1, tid2;     void        *tret;     err = pthread_create(&tid1, NULL, thr_fn1, (void *)1);     if (err != 0)         err_quit("can't create thread 1: %s\n", strerror(err));     err = pthread_create(&tid2, NULL, thr_fn2, (void *)1);     if (err != 0)         err_quit("can't create thread 2: %s\n", strerror(err));     err = pthread_join(tid1, &tret);       if (err != 0)         err_quit("can't join with thread 1: %s\n", strerror(err));     printf("thread 1 exit code %d\n", (int)tret);     err = pthread_join(tid2, &tret);     if (err != 0)         err_quit("can't join with thread 2: %s\n", strerror(err));     printf("thread 2 exit code %d\n", (int)tret);     exit(0); } 

By now, you should begin to see similarities between the thread functions and the process functions. Figure 11.6 summarizes the similar functions.

Figure 11.6. Comparison of process and thread primitives

Process primitive

Thread primitive

Description

fork

pthread_create

create a new flow of control

exit

pthread_exit

exit from an existing flow of control

waitpid

pthread_join

get exit status from flow of control

atexit

pthread_cancel_push

register function to be called at exit from flow of control

getpid

pthread_self

get ID for flow of control

abort

pthread_cancel

request abnormal termination of flow of control


By default, a thread's termination status is retained until pthread_join is called for that thread. A thread's underlying storage can be reclaimed immediately on termination if that thread has been detached. When a thread is detached, the pthread_join function can't be used to wait for its termination status. A call to pthread_join for a detached thread will fail, returning EINVAL. We can detach a thread by calling pthread_detach.

 #include <pthread.h> int pthread_detach(pthread_t tid); 

Returns: 0 if OK, error number on failure


As we will see in the next chapter, we can create a thread that is already in the detached state by modifying the thread attributes we pass to pthread_create.

    team bbl



    Advanced Programming in the UNIX Environment
    Advanced Programming in the UNIX Environment, Second Edition (Addison-Wesley Professional Computing Series)
    ISBN: 0321525949
    EAN: 2147483647
    Year: 2005
    Pages: 370

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net