《APUE》:线程清理处理程序


《Unix环境高级编程》这本书附带了许多短小精美的小程序,我在阅读此书的时候,将书上的代码按照自己的理解重写了一遍(大部分是抄书上的),加深一下自己的理解(纯看书太困了,呵呵)。此例子在Ubuntu 10.04上测试通过。

相关链接

  • 《UNIX环境高级编程》(第二版)apue.h的错误
  • Unix环境高级编程 源代码地址

程序简介:这个程序演示了如何使用线程清理处理程序,并解释了其中涉及的清理机制。

  1. //《APUE》程序11-4:线程清理处理程序   
  2. #include <unistd.h>   
  3. #include <stdio.h>   
  4. #include <stdlib.h>   
  5. #include <pthread.h>   
  6.   
  7. void cleanup(void *arg)  
  8. {  
  9.     printf("cleanup: %s\n", (char*)arg);  
  10. }  
  11.   
  12. void *thr_fn1(void *arg)  
  13. {  
  14.     printf("thread 1 start\n");  
  15.     pthread_cleanup_push(cleanup, "thread 1 first handler");  
  16.     pthread_cleanup_push(cleanup, "thread 1 second handler");  
  17.     printf("thread 1 push complete\n");  
  18.     if( arg )  
  19.         return (void*)1;  
  20.     pthread_cleanup_pop(0);  
  21.     pthread_cleanup_pop(0);  
  22.     return (void*)1;  
  23. }  
  24.   
  25. void *thr_fn2(void *arg)  
  26. {  
  27.     printf("thread 2 start\n");  
  28.     pthread_cleanup_push(cleanup, "thread 2 first handler");  
  29.     pthread_cleanup_push(cleanup, "thread 2 second handler");  
  30.     printf("thread 2 push complete\n");  
  31.     if( arg )  
  32.         pthread_exit( (void*)2 );  
  33.     pthread_cleanup_pop(0);  
  34.     pthread_cleanup_pop(0);  
  35.     pthread_exit( void*)2 );  
  36. }  
  37.   
  38. int main(void)  
  39. {  
  40.     pthread_t tid1, tid2;  
  41.     void *tret;  
  42.   
  43.     pthread_create(&tid1, NULL, thr_fn1, (void*)1);  
  44.     pthread_create(&tid2, NULL, thr_fn2, (void*)1);  
  45.     pthread_join(tid1, &tret);  
  46.     printf("thread 1 exit code\n", (int)tret);  
  47.     pthread_join(tid2, &tret);  
  48.     printf("thread 2 exit code\n", (int)tret);  
  49.     return 0;  
  50. }  

运行示例(红色字体的为输入):

www.bkjia.com @ubuntu:~/code$ gcc temp.c -lpthread -o temp
www.bkjia.com @ubuntu:~/code$ ./temp

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
thread 2 exit code

注解:
1:两个子线程都正确启动和退出了
2:如果线程是通过从它的启动线程中返回而终止的话,那么它的清理处理函数就不会被调用。
3:必须把pthread_cleanup_push的调用和pthread_cleanup_pop的调用匹配起来,否则程序通不过编译。

相关内容