1. 首先pthread_cond_wait 的定義是這樣的
The pthread_cond_wait() and pthread_cond_timedwait() functions are used to block on a condition variable. They are called with mutex locked by the calling thread or undefined behaviour will result.
These functions atomically release mutex and cause the calling thread to block on the condition variable cond;atomically here means "atomically with respect to access by anotherthread to the mutex and then the condition variable". That is, ifanother thread is able to acquire the mutex after the about-to-blockthread has released it, then a subsequent call topthread_cond_signal() or pthread_cond_broadcast() in that thread behaves as if it were issued after the about-to-block thread has blocked.
2. 由上解釋可以看出,pthread_cond_wait() 必須與pthread_mutex 配套使用。(wait的內部操作:一進入wait狀態就unclock,在wait結束前lock)
pthread_cond_wait()函數一進入wait狀態就會自動release mutex.
In Thread1:
pthread_mutex_lock(&m_mutex);
pthread_cond_wait(&m_cond,&m_mutex);
pthread_mutex_unlock(&m_mutex);
In Thread2:
pthread_mutex_lock(&m_mutex);
pthread_cond_signal(&m_cond);
pthread_mutex_unlock(&m_mutex);
為什麼要與pthread_mutex 一起使用呢?這是為了應對線程1在調用pthread_cond_wait()但線程1還沒有進入wait cond的狀態的時候,此時線程2調用了cond_singal 的情況。 如果不用mutex鎖的話,這個cond_singal就丟失了。加了鎖的情況是,線程2必須等到 mutex被釋放(也就是 pthread_cod_wait() 進入wait_cond狀態 並自動釋放mutex) 的時候才能調用cond_singal(前提:線程2也使用mutex)。
3. pthread_cond_wait() 一旦wait成功獲得cond 條件的時候會自動 lock mutex.
這就會出現另一個問題。這是因為
The pthread_cond_wait() and pthread_cond_timedwait() is a cancellation point.
In Thread3:
pthread_cancel(&m_thread);
pthread_join();
因為pthread_cond_wait() and pthread_cond_timedwait() 是線程退出點函數,因此在Thread3中
可以調用pthread_cancel()來退出線程1。那樣顯然線程1會在pthread_cond_wait(&m_cond,&m_mutex); 和pthread_mutex_unlock(&m_mutex); 之間退出, pthread_cond_wait()函數返回後自動lock住了mutex,這個時候線程1退出(並沒有運行到pthread_mutex_unlock()),如果Thread2這個時候就再也得不到lock狀態了。
通常解決這個問題的辦法如下
void cleanup(void *arg)
{
pthread_mutex_unlock(&mutex);
}
void* thread1(void* arg)
{
pthread_cleanup_push(cleanup, NULL); // thread cleanup handler
pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex);
pthread_mutex_unlock(&mutex);
pthread_cleanup_pop(0);
}