2015-09-28 208 views
1

關於下面的代碼,我的理解是線程1抓住鎖,檢查條件,解鎖時鐘,將自己設置爲睡眠狀態。之後,線程2聲明相同的鎖定和增加計數,然後喚醒睡眠線程。我的問題是,現在的情況仍然是錯誤的,但它喚醒了睡眠線程,會發生什麼?而條件變量也是一組線程,所以如果有很多線程同時執行代碼,wait()如何處理這種情況呢?最後請解釋一下這段代碼的正確執行順序,非常感謝!關於pthread_cond_wait的困惑

thread 1: 
    pthread_mutex_lock(&mutex); 
    while (!condition) 
     pthread_cond_wait(&cond, &mutex); 
    /* do something that requires holding the mutex and condition is true */ 
    pthread_mutex_unlock(&mutex); 

thread2: 
    while(1){ 
    pthread_mutex_lock(&mutex); 
    count++; 
    pthread_cond_signal(&cond); 
    pthread_mutex_unlock(&mutex); 
    } 
+0

你認爲'while(!condition)'做什麼?只要條件不成立,線程1將繼續重新運行while循環的主體,即它將一直等待該條件。 – immibis

+0

@immibis第二次解鎖是做什麼的?只需解鎖鎖wait()返回? –

+0

第二次解鎖? – immibis

回答

0

我的問題是,條件,現在仍然是假的,但它 喚醒沉睡的線程,會發生什麼?

這就是爲什麼pthread_cond_waitwhile循環。它僅在while環路中出現,當pthread_cond_wait解鎖時條件成立。

而這正是pthread_cond_wait man page筆記需要完成的。

當使用條件變量總是有一個布爾謂詞 涉及與每個條件等待是 真,如果線程應進行相關的共享變量。可能會發生 pthread_cond_timedwait()或pthread_cond_wait()函數的虛假喚醒。 由於從pthread_cond_timedwait()或pthread_cond_wait() 返回並不意味着此謂詞的值,因此在返回時應重新評估謂詞。

(Emphasis mine)。

0

1)線索1鎖 2)線索1解鎖互斥量(與調用pthread_cond_wait互斥) 3)Thtead 2鎖定互斥 4)線程2解鎖互斥量併發送信號(pthraed_cond_signal)5)螺紋1gets互斥量回 6)線程1解鎖互斥鎖