歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 《APUE》:線程清理處理程序

《APUE》:線程清理處理程序

日期:2017/3/1 10:10:02   编辑:Linux編程

《Unix環境高級編程》這本書附帶了許多短小精美的小程序,我在閱讀此書的時候,將書上的代碼按照自己的理解重寫了一遍(大部分是抄書上的),加深一下自己的理解(純看書太困了,呵呵)。此例子在Ubuntu 10.04上測試通過。

相關鏈接

  • 《UNIX環境高級編程》(第二版)apue.h的錯誤 http://www.linuxidc.com/Linux/2011-04/34662.htm
  • Unix環境高級編程 源代碼地址 http://www.linuxidc.com/Linux/2011-04/34826.htm

程序簡介:這個程序演示了如何使用線程清理處理程序,並解釋了其中涉及的清理機制。

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

運行示例(紅色字體的為輸入):

www.linuxidc.com @ubuntu:~/code$ gcc temp.c -lpthread -o temp
www.linuxidc.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的調用匹配起來,否則程序通不過編譯。

Copyright © Linux教程網 All Rights Reserved