APUE2勘误-11.5节 线程终止(关于线程清理处理程序)
生活随笔
收集整理的這篇文章主要介紹了
APUE2勘误-11.5节 线程终止(关于线程清理处理程序)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
平臺:Linux 2.6.28-19-generic
書中講解所用的linux版本為Linux 2.4.22,我沒有在此版本上做實驗的機會,只是在當前用的版本上做了測試,問題原因可能是Linux內核版本升級導致對線程終止的處理方式進行了改動。
代碼如下:
1 #include "apue.h"2 #include <pthread.h>
3
4 void
5 cleanup(void *arg)
6 {
7 printf("cleanup: %s\n", (char *)arg);
8 }
9
10 void *
11 thr_fn1(void *arg)
12 {
13 printf("thread 1 start\n");
14 pthread_cleanup_push(cleanup, (void*)"thread 1 first handler");
15 pthread_cleanup_push(cleanup, (void*)"thread 1 second handler");
16 printf("thread 1 push complete\n");
17 if (arg)
18 return((void *)1);
19 pthread_cleanup_pop(0);
20 pthread_cleanup_pop(0);
21 return((void *)1);
22 }
23
24 void *
25 thr_fn2(void *arg)
26 {
27 printf("thread 2 start\n");
28 pthread_cleanup_push(cleanup, (void*)"thread 2 first handler");
29 pthread_cleanup_push(cleanup, (void*)"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
39 main(void)
40 {
41 int err;
42 pthread_t tid1, tid2;
43 void *tret;
44
45 err = pthread_create(&tid1, NULL, thr_fn1, (void *)1);
46 if (err != 0)
47 err_quit("can't create thread 1: %s\n", strerror(err));
48 err = pthread_create(&tid2, NULL, thr_fn2, (void *)1);
49 if (err != 0)
50 err_quit("can't create thread 2: %s\n", strerror(err));
51 err = pthread_join(tid1, &tret);
52 if (err != 0)
53 err_quit("can't join with thread 1: %s\n", strerror(err));
54 printf("thread 1 exit code %d\n", (int)tret);
55 err = pthread_join(tid2, &tret);
56 if (err != 0)
57 err_quit("can't join with thread 2: %s\n", strerror(err));
58 printf("thread 2 exit code %d\n", (int)tret);
59 exit(0);
60 }
程序運行結果:
1 thread 1 start2 thread 1 push complete
3 cleanup: thread 1 second handler
4 cleanup: thread 1 first handler
5 thread 2 start
6 thread 2 push complete
7 cleanup: thread 2 second handler
8 cleanup: thread 2 first handler
9 thread 1 exit code 1
10 thread 2 exit code 2
在原書中提到,
當線程執(zhí)行以下動作時調用清理函數,
1.調用pthread_exit時;
2.響應取消請求時;
3.用非零execute函數調用pthread_cleanup_pop時。
注意,并不包括線程執(zhí)行return函數,對應的在原書中給出的編程結果,沒有程序運行結果中給出的第3、4行,也即線程1的線程清理函數是沒有被執(zhí)行的。但實際運行情況是,在Linux 2.6版本中,線程執(zhí)行函數通過return返回,也會執(zhí)行線程清理。
因此,需要對線程清理函數的觸發(fā)條件,以及對應的執(zhí)行結果作相應的update。
現在還有一個疑問:
線程執(zhí)行環(huán)境中調用return返回和調用pthread_exit返回有什么區(qū)別嗎?(return本身也要求將返回值顯示轉換成void*)
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的APUE2勘误-11.5节 线程终止(关于线程清理处理程序)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Log4net 在framework C
- 下一篇: request.getRealPath不