# Include <pthread. h> # Include <stdio. h> ? ? // Pthread_cleanup_push and pthread_cleanup_pop shocould be called in pairs at the same lexical nesting level // They are implemented '{''}' ? // Pthread_cleanup_pop with non-zero argument/pthread_cancel/pthread_exit // Will cause the remained handler to be popped and executed ? # Define error printf ("error @ % s line % d \ n", _ file __, _ line __); ? Void thread_cleanup (void * Arg) { // _ FUNC _ can be used instead Printf ("% s is called \ n", _ function __); } ? Void * threadfn (void * Data) { Pthread_cleanup_push(Thread_cleanup, null ); ? // Sleep is a function that can cancel execution threads. It is called the cancellation point [see man 7 pthreads ]; Sleep (20 ); ? Pthread_cleanup_pop(1 ); } ? Int main (INT argc, char const * argv []) { Pthread_t thread; ? If (pthread_create (& Thread, null, threadfn, null )) { Error; Return-1; } ? Sleep (1 ); ? // Cancel the thread before it exits If (Pthread_cancel(Thread )) { Error; Return-1; } ? // Wait for thread to complete it's cleanup If (Pthread_join(Thread, null )) { Error; Return-1; } ? Printf ("done! \ N "); ? Return 0; } |