待补充....................
函数
函数原型
this
void pthread_cleanup_push(void (*routine)(void*), void *arg); void pthread_cleanup_pop(int execute);//这里的int参数,0是不执行push的内容,非0是执行。
三种状况触发回调函数:线程
一、调用pthread_cancel()删除线程。code
二、调用ptread_exit()推出线程。原型
三、调用pthread_cleanup_pop(1)时参数不为0。
回调函数
#include <pthread.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> pthread_t thread1, thread2; void cleanUp(void * arg)//线程清理回调函数 { printf("%s\n", "cleanUp"); } void * thread1Func(void *arg)线程一 { pthread_cleanup_push(cleanUp, "this is cleanUp") printf("%s\n","sadf"); sleep(4); pthread_cleanup_pop(0); //必定要在调用pthread_exit()函数 以前调用pthread_cleanup_pop()函数,cleanup函数才能被调用,由于pop弹出以前才能被调用嘛 pthread_exit((void *)1);//没法触发回调cleanup } void * thread2Func(void *arg) { pthread_cleanup_push(cleanUp, "this is cleanUp") printf("%s\n","sadf"); sleep(4); pthread_exit(0);//触发回调cleanup pthread_cleanup_pop(0); } int main() { pthread_create(&thread1, NULL, (void *)thread1Func, NULL); pthread_create(&thread2, NULL, (void *)thread2Func, NULL); sleep(1); pthread_cancel(thread1);//触发回调 pthread_cancel(thread2);//触发回调 sleep(4); // pthread_join(thread1,NULL); // pthread_join(thread2,NULL); return 0; }