线程4——清理

╄→尐↘猪︶ㄣ 提交于 2019-12-01 09:05:36

 

void pthread_cleanup_push(void (*routine)(void *),void *arg);

  第一个参数:指向需要执行的函数   arg为该函数的参数

void pthread_cleanup_pop(int execute);

  int整形数字,非零为执行清理函数

两个函数成对使用

先把函数写进routine里,调用push函数去装routine,然后在用pop让push发挥作用

什么时候会触发push函数?

1、线程结束时,调用pthread_exit()

2、取消线程相应pthread_cancel

3、非零参数调用pthread_cleanup_pop()

 

1     pthread_cleanup_push(cleanup_handler1,(void*)1);
2     pthread_cleanup_push(cleanup_handler2,(void*)2);
3     pthread_cleanup_push(cleanup_handler3,(void*)3);
4     //按照1、2、3函数顺序进行压栈
5 
6     pthread_cleanup_pop(1);
7     pthread_cleanup_pop(1);
8     pthread_cleanup_pop(1);
9     pthread_exit(0);

最先被执行的时handler3,然后handler2 1

 

 

线程清理示例:

 1 void* thread1(void *arg)
 2 {
 3     int *p;
 4     p = (int *)malloc(sizeof(int));
 5         pthread_cleanup_push(cleanup_handler,(void*)3);
 6         pthread_mutex_lock(&lock);
 7         //此线程主要功能代码
 8         //…….
 9         pthread_cleanup_pop(1);
10 
11 }
12 void cleanup_handler (void *arg)
13 {
14     free(arg);
15         pthread_mutex_unlock(&lock);
16 }

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!