2011-09-22 119 views
2

我正在寫一個簡單的生產者/消費者程序,以更好地理解C++和多線程。 在我的線程運行過的消費者,我有這些前兩行:C++簡單線程問題

pthread_cond_wait(&storageCond, &storageMutex); 
    pthread_mutex_lock(&storageMutex); 

但程序卡住了,可能是一個僵局。 然後我換行:

pthread_mutex_lock(&storageMutex); 
    pthread_cond_wait(&storageCond, &storageMutex); 

和它的工作。 有人可以幫我理解爲什麼這個工作,前者沒有?

謝謝。

回答

5

從調用pthread_cond_wait手冊頁(http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cond_wait.html):

他們被稱爲與互斥調用線程或未定義 行爲將導致鎖定。

我建議你使用一些好的包裝庫像boost::threads,或當你有機會獲得C++ 11使用std::線程設施。由於他們使用像RAII這樣的東西,他們更容易處理,特別是在線程編程方面沒有經驗的時候。

1

這是一個簡單的,但你基本上需要對你正在使用的互斥鎖進行鎖定,以等待狀態 - 它像多線程競爭條件保護。如果你需要的爲什麼,用「man調用pthread_cond_wait」檢查UNIX man頁面一個很好的說明和一旦線程從條件變量等待恢復它給出了一個很好的長篇大論:)

pthread_cond_wait(&storageCond, &storageMutex); //Wants mutex you don't have locked. 
pthread_mutex_lock(&storageMutex);    //Get mutex after its too late. 

pthread_mutex_lock(&storageMutex);    //Get mutex first. 
pthread_cond_wait(&storageCond, &storageMutex); //Do cond wait with mutex you have. 
1

,它重新aquires的互斥鎖。這就是爲什麼第一個示例程序卡住了。

這個想法是總是在裏面做一個cond_wait()這個互斥鎖。 cond_wait()會放棄鎖並自動開始等待(這樣就不會錯過來自另一個線程的cond_signal()),並且在發信號時,cond_wait()將重新獲取該互斥鎖以確保關鍵部分只有一個線程在其中運行。

HTH,這種鎖定方案被稱爲Monitor