主线程可以通道 pthread_cancel 主动终止子线程,但是子线程中可能还有未被释放的资源,比如malloc开辟的空间。如果不清理,很有可能会造成内存泄漏。
// 子线程回调函数
void* thread_run(void* args)
{int* p = (int*)malloc(100); // 动态开辟内存pthread_testcancel(); // 设置取消点free(p);p = NULL;// ...
}
因此,为了避免这种情况,于是就有了一对线程清理函数 pthread_cleanup_push 和 pthread_cleanup_pop 。两者必须是成对存在的,否则无法编译通过。
目录
1、pthread_cleanup_push
2、pthread_cleanup_pop
3、实际应用
(1) 子线程主动退出 (pthread_exit)
(2) 子线程被主线程取消 (pthread_cancel)
(3) pthread_cleanup_pop的参数为非0值
pthread_cleanup_push 的作用是创建栈帧,设置回调函数,该过程相当于入栈。回调函数的执行与否有以下三种情况:
第一个参数 routine:回调清理函数。当上面三种情况的任意一种存在时,回调函数就会被调用
第二个参数 args:要传递个回调函数的参数
pthread_cleanup_pop 函数的作用是执行回调函数 或者 销毁栈帧,该过程相当于出栈。根据传入参数的不同执行的结果也会不同。
当 execute = 0 时, 处在栈顶的栈帧会被销毁,pthread_cleanup_push的回调函数不会被执行
当 execute != 0 时,pthread_cleanup_push 的回调函数会被执行。
pthread_cleanup_push 和pthread_cleanup_pop 必须是成对存在的,否则无法编译通过。
这里 pthread_cleanup_pop 函数的放置位置和参数需要注意:
void* pthread_cleanup(void* args){printf("线程清理函数被调用了\n");
}void* pthread_run(void* args)
{pthread_cleanup_push(pthread_cleanup, NULL);pthread_exit((void*)1); // 子线程主动退出pthread_cleanup_pop(0); // 这里的参数要为0,否则回调函数会被重复调用
}int main(){pthread_t tid;pthread_create(&tid, NULL, pthread_run, NULL);sleep(1);pthread_join(tid, NULL);return 0;
}
这里 pthread_cleanup_pop 的放置位置和参数 同上。
void* pthread_cleanup(void* args){printf("线程清理函数被调用了\n");
}void* pthread_run(void* args)
{pthread_cleanup_push(pthread_cleanup, NULL);pthread_testcancel(); // 设置取消点pthread_cleanup_pop(0); // 这里的参数要为0,否则回调函数会被重复调用
}int main(){pthread_t tid;pthread_create(&tid, NULL, pthread_run, NULL);pthread_cancel(tid); // 取消线程sleep(1);pthread_join(tid, NULL);return 0;
}
void* pthread_cleanup(void* args){printf("线程清理函数被调用了\n");
}void* pthread_run(void* args)
{pthread_cleanup_push(pthread_cleanup, NULL);pthread_cleanup_pop(1); // 这里的参数为非0值
}int main(){pthread_t tid;pthread_create(&tid, NULL, pthread_run, NULL);sleep(1);pthread_join(tid, NULL);return 0;
}