- 概要
在线程正常或非正常退出时都需要清理线程所占用的资源,pthread_cleanup_push 和 pthread_cleanup_pop函数在线程退出时可以执行指定清理函数
pthread_cleanup_pop(0),当调用了pthread_cancel() 函数或pthread_exit()时执行指定清理函数。一般pthread_cleanup_pop函数只有参数大于0才会执行指定清理函数
名称 | pthread_cleanup_push / pthread_cleanup_pop |
功能 | 线程清理函数入栈 / 线程清理函数出栈 |
头文件 | #include<pthread.h> |
原型 | pthread_cleanup_push(void (*rnt)(void *), void *arg) pthread_cleanup_pop(int execute) |
参数 | *rnt : 需要执行线程清理函数入口 execute : 执行标示 0 不执行; 1 执行 |
返回 | 无 |
#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
void cleanup(void *arg)
{
printf("cleanup : %s\n", (char*)arg);
}
void *child_one(void *arg)
{
printf("thread one start\n");
pthread_cleanup_push(cleanup, "thread one cleapup first\n");
pthread_cleanup_push(cleanup, "thread one cleanup second\n");
printf("thread one push complete\n");
if(arg)
{
return ((void*)1);
}
pthread_cleanup_pop(0);
pthread_cleanup_pop(0);
return ((void*)1);
}
void child_two(void *arg)
{
printf("thread two start\n");
pthread_cleanup_push(cleanup, "thread two cleanup first\n");
pthread_cleanup_push(cleanup, "thread two cleanup second\n");
printf("thread two push complete\n");
if(arg)
{
pthread_exit((void*)2);
}
pthread_cleanup_pop(cleanup, "thread two cleanup first\n");
pthread_cleanup_pop(cleanup, "thread two cleanup second\n");
pthread_exit((void*)2);
}
void main()
{
pthread_t child1, child2;
void *tret;
pthread_create(&child1, NULL, child_one, NULL);
pthread_create(&child2, NULL, child_two, NULL);
pthread_join(child1, &tret);
pthread_join(child2, &tret);
}
执行结果:
执行结果中没有调用child_one函数中的pthread_cleanup_push方法中设定的线程清理函数,因为在child_one函数中pthread_cleanup_pop方法中参数为0,并且又没有调用pthread_cancel 和 pthread_exit方法