Pthread_cond_wait 迴圈條件檢查

來源:互聯網
上載者:User

 

       條件變數是線程一種可以同步機制。條件本身是由互斥變數保護的。線程在改變條件狀態前必須要鎖定互斥變數以後才能計算。

       Pthread_cond_wait(pthread_cond_t*  cond,pthread_mutex_t* mutex);

       Pthread_cond_wait的主要工作方式:

       傳遞給pthread_cond_wait的互斥變數對條件進行保護,調用者把鎖住的互斥量傳遞給函數。函數把調用線程放到等待條件的線程列表上,然後對互斥量解鎖,這兩個操作就是原子操作。這樣就關閉了條件檢查和線程進入休眠狀態等待條件改變這兩個操作之前的時間通道。Pthread_cond_wait返回時,互斥量再次鎖住。

       總結,pthread_cond_wait內部操作:

            1) 
解鎖;

            2) 
接收到signal,函數準備返回;

            3) 
上鎖

      

APUE的典型代碼:

       #include<pthread.h>

       Struct msg{

              Struct msg* m_next;

              /*more stuff here*/

       }

       Struct msg *workq;

       Pthread_cond_t qready = PTHREAD_COND_INITIALIZER;

       Pthread_mutex_t qlock=PTHREAD_MUTEX_INITIALIZER;

      

Void
process_msg(){

       Struct msg* mq;

While(1){

       Pthread_mutex_lock(qlock);

       While(workq == NULL)      

              Pthread_cond_wait(&qready
,&qlock);

       Mq = workq;

       Workq = workq->m_next;

       Pthread_mutex_unlock(qlock);

}
}

      

              Void
enqueue_msg(struct msg* mp){

                     Pthread_mutex_lock(&qlock);

                     Mp->m_next
= workq;

                     Pthread_mutex_unlock(&qlock);

                     Pthread_cond_signal(&qready);

              }

 

              

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.