对pthread_cond_wait()函数的理解
?對pthread_cond_wait()函數的理解(我在CU上回復一個人的問題的解答) (個人見解,如有錯誤,懇請大家指出) /************pthread_cond_wait()的使用方法**********/???? pthread_mutex_lock(&qlock);??????? pthread_cond_wait(&qready, &qlock);???? pthread_mutex_unlock(&qlock); /*****************************************************/ The mutex passed to pthread_cond_wait protects the condition.The caller passes it locked to the function, which then atomically places the calling thread on the list of threads waiting for the condition and unlocks the mutex. This closes the window between the time that the condition is checked and the time that the thread goes to sleep waiting for the condition to change, so that the thread doesn't miss a change in the condition. When pthread_cond_wait returns, the mutex is again locked. 上面是APUE的原話,就是說pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex)函數傳入的參數mutex用于保護條件,因為我們在調用pthread_cond_wait時,如果條件不成立我們就進入阻塞,但是進入阻 塞這個期間,如果條件變量改變了的話,那我們就漏掉了這個條件。因為這個線程還沒有放到等待隊列上,所以調用pthread_cond_wait前要先鎖 互斥量,即調用pthread_mutex_lock(),pthread_cond_wait在把線程放進阻塞隊列后,自動對mutex進行解鎖,使得 其它線程可以獲得加鎖的權利。這樣其它線程才能對臨界資源進行訪問并在適當的時候喚醒這個阻塞的進程。當pthread_cond_wait返回的時候又自動給mutex加鎖。 實際上邊代碼的加解鎖過程如下: /************pthread_cond_wait()的使用方法**********/ pthread_mutex_lock(&qlock);??? /*lock*/ pthread_cond_wait(&qready, &qlock); /*block-->unlock-->wait() return-->lock*/ pthread_mutex_unlock(&qlock); /*unlock*/ /*****************************************************/
轉載于:https://www.cnblogs.com/hdjsjlbs/p/3324332.html
總結
以上是生活随笔為你收集整理的对pthread_cond_wait()函数的理解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: [转]Redis集群的配置
- 下一篇: 学习Berkeley DB- 入门