1. Multiple threads are executed in the specified order, that is, thread synchronization
2. Conditional variables for thread synchronization
Initialization: pthread_cond_t cond_ready = pthread_cond_initializer; wait condition mature: pthread_cond_wait (&cond_ready,&mut); Set maturity Condition: pthread_cond_signal (&cond_ready);
3. General examples
/*********************************************************************** * FILE_NAME:SYNC.C * Description: A first sweep 5 times after the B tow once to ***********************************************************************/#include <stdio.h># Include <pthread.h>pthread_t thread[2];int number = 0;pthread_mutex_t mut;pthread_cond_t Cond_ready = PTHREAD_ Cond_initializer;void Studenta () {int i;for (i=0; i<5; i++) {pthread_mutex_lock (&mut);//Sweep once to number++;if (number >=5) {printf ("Student A has finished he work!\n");//notify B classmate Pthread_cond_signal (&cond_ready);} Pthread_mutex_unlock (&mut);//rest 1 seconds sleep (1);} Exit Pthread_exit (NULL);} void Studentb () {pthread_mutex_lock (&mut); if (number<5) {//waits for the wake of a, this function automatically locks pthread_cond_wait (&cond_ready , &mut);} Number = 0;pthread_mutex_unlock (&mut);p rintf ("Student B has finished he work!\n");//Exit Pthread_exit (NULL);} int main () {//Initialize Mutex lock Pthread_mutex_init (&mut,null);//Create a classmate thread Pthread_create (&thread[0],null,studenta,null) ;//create B classmate Thread Pthread_create (&tHread[1],null,studentb,null);//wait for a classmate thread to end Pthread_join (thread[0],null);//wait for the Class B thread to end Pthread_join (thread[1],null);}
Multi-threaded synchronization