Turn from: http://blog.sina.com.cn/s/blog_6ffd3b5c0100mc3n.html
Give an example (http://blog.csdn.net/KataDoc360/archive/2009/02/16/3897957.aspx): pthread_mutex_t count_lock;
pthread_cond_t Count_nonzero;
unsigned count = 0;
Decrement_count () {
Pthread_mutex_lock (&count_lock);
while (count==0)
Pthread_cond_wait (&count_nonzero, &count_lock);//This function will unlock first, then block the wait condition variable, the last lock
count=count-1;
Pthread_mutex_unlock (&count_lock);
} increment_count () {
Pthread_mutex_lock (&count_lock); if (count==0)
Pthread_cond_signal (&count_nonzero); count=count+1;
Pthread_mutex_unlock (&count_lock);
}
Decrement_count and Increment_count are called in two threads A and B. In the right case, if Decrement_count first runs, then a will be blocked to pthread_cond_wait. Then Increment_count runs, which calls Pthread_cond_signal wakeup wait condition lock Count_nonzero a thread, but a thread does not execute immediately because it does not have a mutex count_lock. A thread can continue execution after the B thread executes pthread_mutex_unlock. This may be the case if the pthread_cond_signal is not used before and after the mutex Count_lock protection. A blocks to pthread_cond_wait, then B executes to pthread_cond_signal, a thread switch occurs, so a wakes up and finds that count is still 0, so it continues to block to the conditional lock Count_nonzero. Then B continues to execute, even though Count=1,a will never be awakened. A logical error occurs. In this context, of course, if the count=count+1 is placed in the function before the pthread_cond_signal becomes Increment_count () {
count=count+1; if (count==0)
Pthread_cond_signal (&count_nonzero);
This is no problem. However, this method does not guarantee that it will apply in all cases. A mutex is then used to protect the variables associated with the conditional lock. That is, conditional locks are used for thread communication, but mutexes are designed to protect the communication from logical errors and work properly.