Multi-threaded synchronization

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.