Document directory
- Time for clearing function calls:
# Include <stdio. h> # include <pthread. h> # include <windows. h> // sleeppthread_mutex_t CTX = pthread_mutex_initializer; pthread_cond_t cond = pthread_cond_initializer; struct node {intnumber; struct node * Next;} * head = NULL; // clear the void cleanup_handler (void * node) {printf ("cleanup handler of second thread. \ n "); free (node); pthread_mutex_unlock (& CTX);} void * thread_func (void * Arg) {struct node * P = NULL; // clear the function into the stack, This demo only requires a cleanup function pthread_cleanup_push (cleanup_handler, P); While (true) {pthread_mutex_lock (& CTX); If (Head = NULL) {pthread_cond_wait (& cond, & mt) ;}p = head; head = head-> next; printf ("got % d from front of queue \ n", p-> number ); free (p); pthread_mutex_unlock (& CTX) ;}/ * If the thread is terminated from this end, it is normal to exit without cleaning. Therefore, you only need to remove the function from the stack. Therefore, zero parameters are used. If you exit from the preceding "cancel point", the function is called when the function is removed from the stack: the lock is opened and resources are released. */Pthread_cleanup_pop (0); Return 0;} int main (INT argc, char * argv []) {pthread_t tid; pthread_create (& tid, null, thread_func, null ); for (INT I = 0; I <10; I ++) {struct node * P = (node *) malloc (sizeof (struct node )); p-> Number = I; // <! -- The head operation is in the critical section pthread_mutex_lock (& CTX); P-> next = head; head = P; pthread_cond_signal (& Cond); pthread_mutex_unlock (& CTX ); // use the mutex lock to protect the lock. --!> Sleep (1);} printf ("main thread wants to cancel the 2nd thread. \ n ");/* For pthread_cancel, there is an additional note that it is used to end the child thread from the external end. The child thread will exit the thread at the latest cancellation point. In our code, the most recent cancellation point is pthread_cond_wait. */Pthread_cancel (TID); pthread_join (TID, null); printf ("all done -- exiting \ n"); Return 0 ;}
Time for clearing function calls:
- When pthread_exit () is called, the cleanup function is called. The thread returned by return is not called.
- Called when canceled by another thread.
- The pthread_cleanup_pop () parameter is called if it is not zero.