深入理解pthread_cond_wait、pthread_cond_signal
===============================man pthread_cond_wait的解釋==========================
LINUX環(huán)境下多線程編程肯定會遇到需要條件變量的情況,此時必然要使用pthread_cond_wait()函數(shù)。但這個函數(shù)的執(zhí)行過程比較難于理解。
??? pthread_cond_wait()的工作流程如下(以MAN中的EXAMPLE為例):
?????? Consider two shared variables x and y, protected by the mutex mut, and a condition vari-
?????? able cond that is to be signaled whenever x becomes greater than y.
????????????? int x,y;
????????????? pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
????????????? pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
?????? Waiting until x is greater than y is performed as follows:
????????????? pthread_mutex_lock(&mut);
????????????? while (x <= y) {
????????????????????? pthread_cond_wait(&cond, &mut);
????????????? }
????????????? /* operate on x and y */
????????????? pthread_mutex_unlock(&mut);
?????? Modifications on x and y that may cause x to become greater than y should signal the con-
?????? dition if needed:
????????????? pthread_mutex_lock(&mut);
????????????? /* modify x and y */
????????????? if (x > y) pthread_cond_broadcast(&cond);
????????????? pthread_mutex_unlock(&mut);
?????這個例子的意思是,兩個線程要修改X和 Y的值,第一個線程當(dāng)X<=Y時就掛起,直到X>Y時才繼續(xù)執(zhí)行(由第二個線程可能會修改X,Y的值,當(dāng)X>Y時喚醒第一個線程),即 首先初始化一個普通互斥量mut和一個條件變量cond。之后分別在兩個線程中分別執(zhí)行如下函數(shù)體:
??????????????pthread_mutex_lock(&mut);
????????????? while (x <= y) {
????????????????????? pthread_cond_wait(&cond, &mut);
????????????? }
????????????? /* operate on x and y */
????????????? pthread_mutex_unlock(&mut);
和:???????pthread_mutex_lock(&mut);
????????????? /* modify x and y */
????????????? if (x > y) pthread_cond_signal(&cond);
????????????? pthread_mutex_unlock(&mut);?
??? 其實函數(shù)的執(zhí)行過程非常簡單,在第一個線程執(zhí)行到pthread_cond_wait(&cond,&mut)時,此時如果X<=Y,則此函數(shù)就將mut互斥量解鎖?,再將cond條件變量加鎖?,此時第一個線程掛起?(不占用任何CPU周期)。
??? 而在第二個線程中,本來因為mut被第一個線程鎖住而阻塞,此時因為mut已經(jīng)釋放,所以可以獲得鎖mut,并且進(jìn)行修改X和Y的值,在修改之后,一個IF語句判定是不是X>Y,如果是,則此時pthread_cond_signal()函數(shù)會喚醒第一個線程?,并在下一句中釋放互斥量mut。然后第一個線程開始從pthread_cond_wait()執(zhí)行,首先要再次鎖mut?, 如果鎖成功,再進(jìn)行條件的判斷?(至于為什么用WHILE,即在被喚醒之后還要再判斷,后面有原因分析),如果滿足條件,則被喚醒?進(jìn)行處理,最后釋放互斥量mut?。
??? 至于為什么在被喚醒之后還要再次進(jìn)行條件判斷(即為什么要使用while循環(huán)來判斷條件),是因為可能有“驚群效應(yīng)”。有人覺得此處既然是被喚醒的,肯定 是滿足條件了,其實不然。如果是多個線程都在等待這個條件,而同時只能有一個線程進(jìn)行處理,此時就必須要再次條件判斷,以使只有一個線程進(jìn)入臨界區(qū)處理。 對此,轉(zhuǎn)來一段:
引用下POSIX的RATIONALE:?
?
Condition Wait Semantics?
?
It is important to note that when pthread_cond_wait() and pthread_cond_timedwait() return without error, the associated predicate may still be false. Similarly, when pthread_cond_timedwait() returns with the timeout error, the associated predicate may be true due to an unavoidable race between the expiration of the timeout and the predicate state change.?
?
The application needs to recheck the predicate on any return because it cannot be sure there is another thread waiting on the thread to handle the signal, and if there is not then the signal is lost. The burden is on the application to check the predicate.?
?
Some implementations, particularly on a multi-processor, may sometimes cause multiple threads to wake up when the condition variable is signaled simultaneously on different processors.?
?
In general, whenever a condition wait returns, the thread has to re-evaluate the predicate associated with the condition wait to determine whether it can safely proceed, should wait again, or should declare a timeout. A return from the wait does not imply that the associated 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在多處理器上可能同時喚醒多個線程,當(dāng)你只能讓一個線程處理某個任務(wù)時,其它被喚醒的線程就需要繼續(xù) wait,while循環(huán)的意義就體現(xiàn)在這里了,而且規(guī)范要求pthread_cond_signal至少喚醒一個pthread_cond_wait上 的線程,其實有些實現(xiàn)為了簡單在單處理器上也會喚醒多個線程.?
2,某些應(yīng)用,如線程池,pthread_cond_broadcast喚醒全部線程,但我們通常只需要一部分線程去做執(zhí)行任務(wù),所以其它的線程需要繼續(xù)wait.所以強(qiáng)烈推薦此處使用while循環(huán).
?????? 其實說白了很簡單,就是pthread_cond_signal()也可能喚醒多個線程,而如果你同時只允許一個線程訪問的話,就必須要使用while來進(jìn)行條件判斷,以保證臨界區(qū)內(nèi)只有一個線程在處理。
pthread_cond_wait()??用于阻塞當(dāng)前線程,等待別的線程使用?pthread_cond_signal()?或pthread_cond_broadcast來喚醒它?。??pthread_cond_wait()???必須與pthread_mutex 配套使用。pthread_cond_wait()?函數(shù)一進(jìn)入wait狀態(tài)就會自動release mutex。當(dāng)其他線程通過?pthread_cond_signal()?或pthread_cond_broadcast?,把該線程喚醒,使?pthread_cond_wait()通過(返回)時,該線程又自動獲得該mutex?。
????????pthread_cond_signal?函數(shù)的作用是發(fā)送一個信號給另外一個正在處于阻塞等待狀態(tài)的線程,使其脫離阻塞狀態(tài),繼續(xù)執(zhí)行.如果沒有線程處在阻塞等待狀態(tài),pthread_cond_signal也會成功返回。
????????使用pthread_cond_signal一般不會有“驚群現(xiàn)象”產(chǎn)生,他最多只給一個線程發(fā)信號。假如有多個線程正在阻塞等待著這個條件變量的話,那么是根據(jù)各等待線程優(yōu)先級的高低確定哪個線程接收到信號開始繼續(xù)執(zhí)行。如果各線程優(yōu)先級相同,則根據(jù)等待時間的長短來確定哪個線程獲得信號。但無論如何一個pthread_cond_signal調(diào)用最多發(fā)信一次。
????????但是?pthread_cond_signal?在多處理器上可能同時喚醒多個線程,當(dāng)你只能讓一個線程處理某個任務(wù)時,其它被喚醒的線程就需要繼續(xù) wait,
==============================另一篇很好的文章===========================
POSIX線程詳解
==============================使用效率問題============================
pthread_cond_signal函數(shù)的作用是發(fā)送一個信號給另外一個正在處于阻塞等待狀態(tài)的線程,使其脫離阻塞狀態(tài),繼續(xù)執(zhí)行.如果沒有線程處在阻塞等待狀態(tài),pthread_cond_signal也會成功返回。
但使用pthread_cond_signal不會有“驚群現(xiàn)象”產(chǎn)生,他最多只給一個線程發(fā)信號。假如有多個線程正在阻塞等待著這個條件變量的話,那么是根據(jù)各等待線程優(yōu)先級的高低確定哪個線程接收到信號開始繼續(xù)執(zhí)行。如果各線程優(yōu)先級相同,則根據(jù)等待時間的長短來確定哪個線程獲得信號。但無論如何一個pthread_cond_signal調(diào)用最多發(fā)信一次。
另外,互斥量的作用一般是用于對某個資源進(jìn)行互斥性的存取,很多時候是用來保證操作是一個原子性的操作,是不可中斷的。
用法:
pthread_cond_wait必須放在pthread_mutex_lock和pthread_mutex_unlock之間,因為他要根據(jù)共享變量的狀態(tài)來決定是否要等待,而為了不永遠(yuǎn)等待下去所以必須要在lock/unlock隊中
共享變量的狀態(tài)改變必須遵守lock/unlock的規(guī)則
pthread_cond_signal即可以放在pthread_mutex_lock和pthread_mutex_unlock之間,也可以放在pthread_mutex_lock和pthread_mutex_unlock之后,但是各有各缺點。
之間:
pthread_mutex_lock
xxxxxxx
pthread_cond_signal
pthread_mutex_unlock
缺點:在某下線程的實現(xiàn)中,會造成等待線程從內(nèi)核中喚醒(由于cond_signal)然后又回到內(nèi)核空間(因為cond_wait返回后會有原子加鎖的行為),所以一來一回會有性能的問題。
在code review中,我會發(fā)現(xiàn)很多人喜歡在pthread_mutex_lock()和pthread_mutex_unlock(()之間調(diào)用 pthread_cond_signal或者pthread_cond_broadcast函數(shù),從邏輯上來說,這種使用方法是完全正確的。但是在多線程環(huán)境中,這種使用方法可能是低效的。posix1標(biāo)準(zhǔn)說,pthread_cond_signal與pthread_cond_broadcast無需考慮調(diào)用線程是否是mutex的擁有者,也就是說,可以在lock與unlock以外的區(qū)域調(diào)用。如果我們對調(diào)用行為不關(guān)心,那么請在lock區(qū)域之外調(diào)用吧。這里舉個例子:
???????我們假設(shè)系統(tǒng)中有線程1和線程2,他們都想獲取mutex后處理共享數(shù)據(jù),再釋放mutex。請看這種序列:
???????1)線程1獲取mutex,在進(jìn)行數(shù)據(jù)處理的時候,線程2也想獲取mutex,但是此時被線程1所占用,線程2進(jìn)入休眠,等待mutex被釋放。
???????2)線程1做完數(shù)據(jù)處理后,調(diào)用pthread_cond_signal()喚醒等待隊列中某個線程,在本例中也就是線程2。線程1在調(diào)用pthread_mutex_unlock()前,因為系統(tǒng)調(diào)度的原因,線程2獲取使用CPU的權(quán)利,那么它就想要開始處理數(shù)據(jù),但是在開始處理之前,mutex必須被獲取,很遺憾,線程1正在使用mutex,所以線程2被迫再次進(jìn)入休眠。
???????3)然后就是線程1執(zhí)行pthread_mutex_unlock()后,線程2方能被再次喚醒。
?????? 從這里看,使用的效率是比較低的,如果再多線程環(huán)境中,這種情況頻繁發(fā)生的話,是一件比較痛苦的事情。
但是在LinuxThreads或者NPTL里面,就不會有這個問題,因為在Linux 線程中,有兩個隊列,分別是cond_wait隊列和mutex_lock隊列, cond_signal只是讓線程從cond_wait隊列移到mutex_lock隊列,而不用返回到用戶空間,不會有性能的損耗。
所以在Linux中推薦使用這種模式。
之后:
pthread_mutex_lock
xxxxxxx
pthread_mutex_unlock
pthread_cond_signal
優(yōu)點:不會出現(xiàn)之前說的那個潛在的性能損耗,因為在signal之前就已經(jīng)釋放鎖了
缺點:如果unlock和signal之前,有個低優(yōu)先級的線程正在mutex上等待的話,那么這個低優(yōu)先級的線程就會搶占高優(yōu)先級的線程(cond_wait的線程),而這在上面的放中間的模式下是不會出現(xiàn)的。
所以,在Linux下最好pthread_cond_signal放中間,但從編程規(guī)則上說,其他兩種都可以
?
來自 <https://blog.csdn.net/yeyuangen/article/details/37593533>
總結(jié)
以上是生活随笔為你收集整理的深入理解pthread_cond_wait、pthread_cond_signal的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mutex的加锁与解锁问题
- 下一篇: C/C++多线程编程之一】VC6.0安装