这是学习APUE的第二遍,今天看到pthread_cleanup_push的时候做了一个小实验,发现了清理机制在c和c++下有些不同,
按照stevens所说的,如果是从线程的入口函数通过return正常返回的话,通过pthread_cleanup_push注册的清理函数将不执行。
在C编译的情况下确实如此,可是当我将代码通过g++以c++的方式编译后,情况发生了变化,通过return返回依然导致了清理函数的运行。
代码如下:
1 #include <iostream>
2 #include <pthread.h>
3 using namespace std;
4
5 void clean_func(void *arg) {
6 cout << "this is :" << pthread_self() << " " << (char *)arg << endl;
7 }
8 //===============================
9 void *func_1(void *arg) {
10 cout << "func1 starting..." << endl;
11 char *str1 = "thread1 cleanup 1..", *str2 = "thread1 cleanup 2...";
12 pthread_cleanup_push(clean_func, (void*)str1);
13 pthread_cleanup_push(clean_func, (void*)str2);
14 cout << "func1 cleanup push completed!" << endl;
15 if (!(int)arg) {
16 cout << "XXXXXXXXXXXXXXXX" << endl;
17 return ((void*)1);
18 // pthread_exit((void*)1);
19 }
20 pthread_cleanup_pop(1);
21 pthread_cleanup_pop(0);
22 return ((void*)1);
23 }
//===============================
25 int main() {
26 pthread_t tid1;
27 int err;
28 void *tret;
29 err = pthread_create(&tid1, NULL, func_1, (void*)1);
30 pthread_join(tid1, &tret);
31 cout << "thread1 exited, code is :" << (int)tret << endl;
32
33 return 0;
34 }