#include <stdio.h>#include<pthread.h>#include<unistd.h>pthread_mutex_t mutex;pthread_cond_t cond;void*child (void*Arg) {Pthread_cleanup_push (Pthread_mutex_unlock,&mutex); while(1) {printf ("Thread1 get running \ n"); printf ("thread1 Pthread_mutex_lock returns%d\n", Pthread_mutex_lock (&mutex)); Pthread_cond_wait (&cond,&mutex); printf ("thread1 Condition applied\n"); Pthread_mutex_unlock (&mutex); Sleep (5); } pthread_cleanup_pop (0);}void*child (void*Arg) { while(1) {Sleep (3);//Note 1printf"thread2 get running \ n"); printf ("thread2 Pthread_mutex_lock returns%d\n", Pthread_mutex_lock (&mutex)); Pthread_cond_wait (&cond,&mutex); printf ("thread2 Condition applied\n"); Pthread_mutex_unlock (&mutex); Sleep (1); }}intMain () {intTid1,tid2; printf ("Hello condition variable test\n"); Pthread_mutex_init (&mutex,null); Pthread_cond_init (&cond,null); Pthread_create (&tid1,null,child1,null); Pthread_create (&tid2,null,child1,null); Do{sleep (2);//The purpose of this statement (note 2) and note 1 is to give TID1 time to complete the Cancel action! Pthread_cancle (TID1);//The program can execute without this statement. Sleep2); Pthread_cond_signal (&cond); } while(1); Sleep ( -); Pthread_exit (0);}//No callback function Pthread_cleanup_push (Pthread_mutex_unlock,&mutex), and Pthread_cleanup_pop (0);//then the system hangs in place of the TID2 request lock.//if the two lines of code such as annotations 1 and 2 are not executed, the child2 can be controlled before the child1 completes the cancellation action, thus successfully executing//the operation for the lock is requested, but may be suspended in pthread_cond_wait (&cond,&mutex), as there are also actions to apply for the mutex//(because the mutex will be re-locked before the condition is satisfied and left pthread_cond_wait (), corresponding to the lock action before entering pthread_cond_wait ()! )
//Child1 gives the use of standard conditional variables: callback function protection, waiting for the condition to be unlocked, pthread_cond_wait (&cond,&mutex), and unlocking after returning.
Use of the Linux callback function