Condition Variables

Goal

如果我們想要等待某個 share resource 達到什麼條件,如果用前兩個介紹的 lock 就必須跟 file lock 一樣頻繁詢問,造成 busy waiting,而使用 condition variable,則就和使用 selectpoll 一樣

Concept

我們宣告一個變數 cond,我們可以告訴 kernel 說我們正在等待這個 condition 並且進入休眠模式,當其他 thread 用這個 cond 發送 signal 時,睡著的 thread 就會被叫醒並且繼續執行

Need to be used with mutex

從上面可以看到,有多個 thread 會存取 cond,因此可能會造成 race condition,因此我們就需要用 mutex 保證每個時刻只會有一個 thread 在存取 cond

Multiple thread can use one cond

我們可以讓多個 thread 同時等待一個 cond


Setting

Init & Destroy

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

thread attributes 中的 init & destroy 很像

Condition Variable Attributes

int pthread_condattr_init (pthread_condattr_t *attr)
int pthread_condattr_destroy (pthread_condattr_t *attr )
  • PTHREAD_PROCESS_SHAREDPTHREAD_PROCESS_PRIVATE 可調
  • mutex attribute 很像

Wait & Signal