1. 程式人生 > >Linux下互斥量與條件變數詳細解析

Linux下互斥量與條件變數詳細解析

引用下POSIX的RATIONALE: 

Condition Wait Semantics 

It is important to note that when pthread_cond_wait() andpthread_cond_timedwait() return without error, the associated predicatemay still be false. Similarly, when pthread_cond_timedwait() returnswith the timeout error, the associated predicate may be true due to anunavoidable race between the expiration of the timeout and thepredicate state change. 

The application needs to recheck the predicate on any return because itcannot be sure there is another thread waiting on the thread to handlethe signal, and if there is not then the signal is lost. The burden ison the application to check the predicate. 

Some implementations, particularly on a multi-processor, may sometimescause multiple threads to wake up when the condition variable issignaled simultaneously on different processors. 

In general, whenever a condition wait returns, the thread has tore-evaluate the predicate associated with the condition wait todetermine whether it can safely proceed, should wait again, or shoulddeclare a timeout. A return from the wait does not imply that theassociated predicate is either true or false. 

It is thus recommended that a condition wait be enclosed in the equivalent of a "while loop" that checks the predicate. 

從上文可以看出: 
1,pthread_cond_signal在多處理器
上可能同時喚醒多個執行緒,當你只能讓一個執行緒處理某個任務時,其它被喚醒的執行緒就需要繼續 wait,while迴圈的意義就體現在這裡了,而且規範要求pthread_cond_signal至少喚醒一個pthread_cond_wait上的執行緒,其實有些實現為了簡單在單處理器上也會喚醒多個執行緒. 
2,某些應用,如執行緒池,pthread_cond_broadcast喚醒全部執行緒,但我們通常只需要一部分執行緒去做執行任務,所以其它的執行緒需要繼續wait.所以強烈推薦此處使用while迴圈.