Search This Blog

Saturday, October 31, 2009

Pthread, Mutex And Conditional Variable

A thread can lock a mutex.
1. if the mutex is already locked (by another thread), the thread is put to slept.
2. the sleeping thread will wake up when the mutex is unlocked by another thread.
3. you can try_lock and get an immediate return

Why we need conditional variable?
1. you want to wait for an event (the conditional variable) to happen (the conditional variable to be signaled)
2. why not just using if i == 1, lock mutex. well...
a. you might need to busy look to check while(i==1)...
b. check and lock in this manner is not atomic. you need to lock the mutex first before checking. what happen if your check succeed, but the conditional has changed right before you try to lock the mutex?

for doing conditional wait:
%always wait for your conditional variable in a while loop%
so you can catch the actual data changed, if predicate does not hold, back to the while loop
(this is NOT a busy loop, because your conditional wait can put you into sleep here)
%always test for your predicate after thew while loop%
so you can detect something is wrong. e.g. how can you leave the "while" checking
but later on your predicate still does not hold? is that on purpose?
a. always try to lock the mutex (associated with the conditional variable) before waiting
b. conditional wait will unlock the mutex before checking the signal
c. if the conditional variable is not signaled, the thread is blocked
d. later the conditional variable is signaled, the wait function will locked the mutex before return
e. remember to unlock the mutex at last.

No comments: