Linux Condition variable condition variables to avoid lock collisions

Source: Internet
Author: User
Tags mutex

General usage of the condition variable condition variable:

Wake-up usage:

1 struct {2 pthread_mutex_t Mutex;3 pthread_cond_t cond;4     //Whatever variables maintain the condition5)var= {Pthread_mutex_initializer, Pthread_cond_initializer, ...};//declaring a struct and initializing it6   7Pthread_mutex_lock (&var. Mutex);8 //Set Condition True9Pthread_cond_signal (&var. Cond):TenPthread_mutex_unlock (&var. Mutex);

Wait for usage:

1 pthread_mutex_lock (&var. Mutex); 2  while (/*condition is false*/) 3 pthread_cond_wait (&var. Cond, &var. Mutex); 4 // Modify Condition 5 pthread_mutex_unlock (&var. Mutex);

Avoid lock conflicts:

There is a case where the waiting thread is dispatched immediately after calling Pthread_cond_signal in the wake-up thread. Then wait for the thread to run immediately and then stop because it cannot get to the lock. In order to not affect the waiting thread to acquire the lock in time, another way to do this is to:

 1  int   dosignal;  2  pthread_mutex_lock (&nready.mutex);  3  dosignal = (Nready.nready = 0  ); 4  nready.nready++;  5  pthread_mutex_unlock (&nready.mutex);  6  //   release the lock first, then wake up the waiting thread  8  if   (dosignal)  9  Pthread_cond_ Signal (&nready.cond); 

That is, the lock is released first and then awakened. This avoids conflicting issues waiting for the thread to request a lock. A lock must be added before calling pthread_cond_wait.

Linux Condition variable condition variables to avoid lock collisions

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.