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