Linux線程同步(4): 條件變數

來源:互聯網
上載者:User

    條件變數分為兩部分: 條件和變數. 條件本身是由互斥量保護的. 線程在改變條件狀態前先要鎖住互斥量. 

1. 初始化:

    條件變數採用的資料類型是pthread_cond_t, 在使用之前必須要進行初始化, 這包括兩種方式:

  • 靜態: 可以把常量PTHREAD_COND_INITIALIZER給靜態分配的條件變數.
  • 動態: pthread_cond_init函數, 是釋放動態條件變數的記憶體空間之前, 要用pthread_cond_destroy對其進行清理.
#include <pthread.h>

int pthread_cond_init(pthread_cond_t *restrict cond, pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t *cond);

成功則返回0, 出錯則返回錯誤編號.

    當pthread_cond_init的attr參數為NULL時, 會建立一個預設屬性的條件變數; 非預設情況以後討論.

 

2. 等待條件:

#include <pthread.h>

int pthread_cond_wait(pthread_cond_t *restrict cond, pthread_mutex_t *restric mutex);
int pthread_cond_timedwait(pthread_cond_t *restrict cond, pthread_mutex_t *restrict mutex, const struct timespec *restrict timeout);

成功則返回0, 出錯則返回錯誤編號.

    這兩個函數分別是阻塞等待和逾時等待.

    等待條件函數等待條件變為真, 傳遞給pthread_cond_wait的互斥量對條件進行保護, 調用者把鎖住的互斥量傳遞給函數. 函數把調用線程放到等待條件的線程列表上, 然後對互斥量解鎖, 這兩個操作是原子的. 這樣便關閉了條件檢查和線程進入休眠狀態等待條件改變這兩個操作之間的時間通道, 這樣線程就不會錯過條件的任何變化.

    當pthread_cond_wait返回時, 互斥量再次被鎖住.

 

3. 通知條件:

#include <pthread.h>

int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);

成功則返回0, 出錯則返回錯誤編號.

    這兩個函數用於通知線程條件已經滿足. 調用這兩個函數, 也稱向線程或條件發送訊號. 必須注意, 一定要在改變條件狀態以後再給線程發送訊號.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.