2013-09-25 265 views
0

首先,我的問題是不同的。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不解開傳遞給它的互斥。這個問題的原因是什麼?

+1

'pthread_cond_wait'總是解鎖互斥量過去了,它這樣做原子w.r.t.等待條件變量;當它返回時,它再次自動鎖定互斥鎖w.r.t.線程再次運行。 'pthread_cond_wait'任一側的任何代碼都將觀察處於鎖定狀態的互斥鎖。 –

+0

請顯示'pthread_mutex_trylock()'循環代碼。該代碼可能存在問題。 – jxh

+0

@AdamRosenfield:你說得對。但在特定情況下,我觀​​察到了這個問題。 jxh:我在調試器中使用pthread_mutex_trylock,而不是在代碼中。 – doptimusprime

回答

0

閱讀pthread_setcancelstate後,我發現pthread_cond_wait是線程的取消點。如果對線程啓用取消並且延遲,則取消點將測試取消。如果有任何取消掛起,線程將退出。

所以,在我的情況下,線程退出留下mutex_鎖定。因此發信號線程塊。

但是還有一個疑問。所有線程都是使用Thread類從相同的函數創建的。爲什麼只有這個線程有這樣的取消行爲?

1

由於@KenThomases指出:你的問題是,你缺少的信號,而不是信號不獲取發送。信號線程在之前調用pthread_cond_signal(),等待線程調用pthread_cond_wait()pthread_cond_wait()只應調用後你測試你正在尋找的不變量當前沒有滿足:

while (!state_) { 
    result = pthread_cond_wait(&cvar_, &mutex_); 
    if (result == EINVAL) ... // error handling 
} 

其他的東西,有時可以幫助就是把信令線程調用pthread_cond_signal()內關鍵部分。這是沒有必要的,以解決您的問題,但可以使程序更易於推理,因爲你知道,沒有其他人持有互斥體的時候,你的信號他們:

// signalling thread 
... 
result = pthread_mutex_lock(&mutex_); 
... 
state_ = 1; 
//signals the condition variable. 
pthread_cond_signal(&cvar_); 
result = pthread_mutex_unlock(&mutex_); 
... 
+0

感謝您的回答。在調試時,我發現等待線程在發送線程信號之前正在進入等待狀態。後來,我發現實際上等待的線程在pthread_cond_wait()上退出,因此使mutex_鎖定。我很快就會發布更多。 – doptimusprime

+0

我加了答案。 – doptimusprime