首先,我的問題是不同的。pthread_cond_wait不解鎖互斥鎖
我的方案中,有一個等待的線程,等待條件變量。信令線程信號條件變量。
我的代碼是
//Wating thread
//Lock the mutex_
//mutex_ is of pthread_mutex_t and is initialized.
result = pthread_mutex_lock(&mutex_);
assert(result == 0);
do {
//Wait on condition variable cvar_
//cva_ is of pthread_cond_t and is initialized.
result = pthread_cond_wait(&cvar_, &mutex_); //POINT 1
}while(result == 0 && !state_);
//Unlock the mutex_.
result = pthread_mutex_unlock(&mutex_);
//signalling thread
result = pthread_mutex_lock(&mutex_); //POINT 2
assert(result == 0);
state_ = 1;
result = pthread_mutex_unlock(&mutex_);
assert(result == 0);
//signals the condition variable.
pthread_cond_signal(&cvar_);
我的操作系統爲Mac OS X 10.8,但最低目標是10.6
這是沒有任何問題幾乎在每一個案件,但一個運行良好。
在特定情況下,我注意到在POINT 1爲pthread_cond_wait
之後,當進入等待狀態時,mutex_未解鎖。這個我通過pthread_mutex_trylock
確認,在這種情況下返回EBUSY。由於這一點,信號線程等待並最終導致死鎖。
我想什麼條件下才知道,pthread_cond_wait
不解開傳遞給它的互斥。這個問題的原因是什麼?
'pthread_cond_wait'總是解鎖互斥量過去了,它這樣做原子w.r.t.等待條件變量;當它返回時,它再次自動鎖定互斥鎖w.r.t.線程再次運行。 'pthread_cond_wait'任一側的任何代碼都將觀察處於鎖定狀態的互斥鎖。 –
請顯示'pthread_mutex_trylock()'循環代碼。該代碼可能存在問題。 – jxh
@AdamRosenfield:你說得對。但在特定情況下,我觀察到了這個問題。 jxh:我在調試器中使用pthread_mutex_trylock,而不是在代碼中。 – doptimusprime