Subj : thread Cleanup handler is not called To : comp.programming.threads From : neelapune Date : Tue Feb 15 2005 10:46 pm Hi, I have been facing the bizaar problem with pthreads in linux. I wanted to invoke my cleanup handler whenever I cancel the thread created. Please refer to the code attached. In my thread routine function "void *thread_routine(void *arg)", there is a while loop inside which i have used a printf, when this printf is a part of the thread function, during thread cancellation my handler is called i.e "void cleanup_handler(void *arg)". Now when i comment the printf and re compile the program(gcc -lpthread sample.c) and run it, during thread cancellation my cleanup handler is not called!!!!. I have failed to understand this logic. Is there any logical or conceptual flaw in my program. I see that printf is not a reentrant or thread safe function, however i am not able to appreciate how that would have anything to do with my function not being called. Any help is greatly appreciated.. Thanks Neela ----------------------------sample.c------------------------------------------ #include #include #include void cleanup_handler(void *arg) { printf("Clean up handler is called\n"); return; } void *thread_routine(void *arg) { pthread_cleanup_push(cleanup_handler,0); int i = 0; while(1) { i++; =====>>> printf("Hai\n"); <<<==== /* * If i comment out the above printf cleanup handler is not called * else cleanup handler is called */ pthread_testcancel(); } pthread_cleanup_pop(1); pthread_exit(0); } int main(int argc, char *argv[]) { pthread_t tid; if (pthread_create(&tid,NULL,thread_routine,0) != 0) { printf("Thread Creation Failed\n"); return 0; } sleep(5); if(pthread_cancel(tid)!=0) { printf("Thread Cancelation Failed\n"); return 0; } return 0; } -------------------------------------Code Ends--------------------------------- .