2012年1月28日 星期六

[PThread] condition variable usage pattern

producer/consumer model. The return value for each pthread function call need to be checked too.

Producer:


while(/* condition for producer to contintue */)
{
pthread_mutex_lock(&mutex);

// do something for producer

// the order of the two following call is not important
// unlock before signal may more efficient than signal before unlock
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cond);
}

Consumer:


while(/* condition for consumer to continue */)
{
// must contain lock before calling condition wait
pthread_mutex_lock(&mutex);

// the condition wait need to be recheck for
// 1. spurious wakeup
// 2. other thread can be waken early
while(/* condition to check for state not valid */)
{
s = pthread_cond_wait(&cond, &mutex);
}
// do consumer work, now under mutex protection
pthread_mutex_unlock(&mutex);
// some other work which don't need mutex
}

Spurious wakeup:
Some condition wait implementation can cause the thread to be waken up when no signal to the condition variable.
man pthreadconidsignal for further detail.