《APUE》:线程清理处理程序
《Unix环境高级编程》这本书附带了许多短小精美的小程序,我在阅读此书的时候,将书上的代码按照自己的理解重写了一遍(大部分是抄书上的),加深一下自己的理解(纯看书太困了,呵呵)。此例子在Ubuntu10.04上测试通过。
程序简介:这个程序演示了如何使用线程清理处理程序,并解释了其中涉及的清理机制。
//《APUE》程序11-4:线程清理处理程序#include <unistd.h>#include <stdio.h>#include <stdlib.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){pthread_t tid1, tid2;void *tret;pthread_create(&tid1, NULL, thr_fn1, (void*)1);pthread_create(&tid2, NULL, thr_fn2, (void*)1);pthread_join(tid1, &tret);printf("thread 1 exit code\n", (int)tret);pthread_join(tid2, &tret);printf("thread 2 exit code\n", (int)tret);return 0;}运行示例(红色字体的为输入):
qch@ubuntu:~/code$ gcc temp.c -lpthread -o temp
qch@ubuntu:~/code$ ./temp
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
thread 2 exit code
注解:
1:两个子线程都正确启动和退出了
2:如果线程是通过从它的启动线程中返回而终止的话,那么它的清理处理函数就不会被调用。
3:必须把pthread_cleanup_push的调用和pthread_cleanup_pop的调用匹配起来,否则程序通不过编译。