待補充....................
函數
函數原型
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; }