linux下的线程学习(二)

 1 #include <iostream>
 2 #include <pthread.h>
 3 
 4 void cleanup(void *arg) {
 5 
 6   printf("cleanup: %s\n", (char*)arg);
 7 }
 8 
 9 void* thr_fn1(void *arg) {
10   
11   printf("thread1 start\n");
12   pthread_cleanup_push(cleanup, (void*)"thread 1 first handler");
13   pthread_cleanup_push(cleanup, (void*)"thread 1 second handler");
14   printf("thread1 push complete.\n");
15   
16   if(arg) {
17     return ((void*)1);
18   }
19 
20   pthread_cleanup_pop(1);
21   pthread_cleanup_pop(1);
22 
23   return ((void*)1);
24 }
25 
26 void* thr_fn2(void *arg) {
27   
28   printf("thread2 start\n");
29   pthread_cleanup_push(cleanup, (void*)"thread 2 first handler");
30   pthread_cleanup_push(cleanup, (void*)"thread 2 second handler");
31   printf("thread2 push complete.\n");
32 
33   if(arg) {
34     pthread_exit((void*)2);
35   }
36 
37   pthread_cleanup_pop(1);
38   pthread_cleanup_pop(1);
39 
40   pthread_exit((void*)2);
41 }
42 
43 int main() {
44 
45   int err;
46   pthread_t tid1,tid2;
47   void *tret;
48 
49   err = pthread_create(&tid1, NULL, thr_fn1, NULL);
50   if(err != 0)
51     printf("can't create thread 1: %s\n", strerror(err));
52 
53   err = pthread_create(&tid2, NULL, thr_fn2, NULL);
54   if(err != 0)
55     printf("can't create thread 2: %s\n", strerror(err));
56 
57   err = pthread_join(tid1, &tret);
58   if(err != 0)
59     printf("can't join with thread 1: %s\n", strerror(err));
60   printf("thread 1 exit code %d\n", (int*)tret );
61 
62   err = pthread_join(tid2, &tret);
63   if(err != 0)
64     printf("can't join with thread 2: %s\n", strerror(err));
65   printf("thread 2 exit code %d\n", (int*)tret );
66 
67   return 0;
68 }

 

 

使用pthread_cleanup_push pthread_cleanup_pop完成线程退出函数自动调用的功能;

posted on 2013-10-10 14:16  笔记吧... 可能只有自己看得懂  阅读(197)  评论(0编辑  收藏  举报