Pthread Condition Variable
man page 對 condition variable 的說明:
A condition (short for ``condition variable’’) is a synchronization device that allows threads to suspend execution and relinquish the processors until some predicate on shared data is satisfied. The basic operations on conditions are: signal the condition (when the predicate becomes true), and wait for the condition, suspending the thread execution until another thread signals the condition.
讓某些 thread suspend 起來,等某個條件成立才繼續往下執行。而另外有些 thread 則會更動條件中變數的值,並在該條件成立時 “signal condition” 叫起在 wait 的 thread 來執行。
A condition variable must always be associated with a mutex, to avoid the race condition where a thread prepares to wait on a condition variable and another thread signals the condition just before the first thread actually waits on it.
condition variable 必須搭配 mutex,避免 race condition:thread A 在 thread B signal condition 後才 wait 這個 condition variable,這種狀況可能讓 thread A 永遠在 sleep(如果沒有人會再 signal 這個 condition variable)。
如果所有 thread 在 signal condition variable 之前都 lock mutex,就能保證 condition 不會在 thread lock mutex 跟 wait condition variable 之間被 signal。或者說是不會在 check 過 condition 到 call wait function 以前其他 thread 就 signal condition variable。
pthread_cond_signal()
會叫起一個正在 wait condition variable 的 thread 來 run。如果沒有 thread 正在 wait,什麼事都不會發生。
pthread_cond_wait()
會 atomically unlcok mutex 並讓 calling thread wait condition variable(suspend 此 thread,suspend 的 thread 不會使用任何 CPU time)。這兩個動作是 atomically 執行的,不會被打斷。
進入 pthread_cond_wait()
前必須先 lock mutex。而 pthread_cond_wait()
在 return(可以 return 是因為有人 signal condition variable)前,會重新 lock 住 mutex。