關於下面的代碼,我的理解是線程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);
}
你認爲'while(!condition)'做什麼?只要條件不成立,線程1將繼續重新運行while循環的主體,即它將一直等待該條件。 – immibis
@immibis第二次解鎖是做什麼的?只需解鎖鎖wait()返回? –
第二次解鎖? – immibis