下面這份代碼是我的書寫方式:
static bool alive = true;
static int count = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void producer()
{
pthread_mutex_lock(&mutex); //加互斥鎖
//...do something here, queue.insert() ...or create something...
count++;
//如果像下面這樣寫,則consumer阻塞到pthread_mutex_lock(&mutex)
//比pthread_cond_wait(&cond, &mutex)先得到互斥鎖控制權。
pthread_mutex_unlock(&mutex); //解互斥鎖
pthread_cond_signal(&cond); //喚醒wait(),如果沒有wait則什麼都不做
//如果像下面這樣寫,則consumer阻塞到pthread_mutex_lock(&mutex)
//比pthread_cond_wait(&cond, &mutex)可能後得到互斥鎖控制權。
pthread_cond_signal(&cond); //喚醒wait(),如果沒有wait則什麼都不做
pthread_mutex_unlock(&mutex); //解互斥鎖
}
void consumer()
{
pthread_mutex_lock(&mutex);//加互斥鎖
while(alive && 0 == count) { //僅在count == 0 時才wait,而且是while()不是if(),經過測試必須得是while,why?
//因為pthread_cond_wait(&cond, &mutex)分為unlock-》wait-》lock,當像producer像第一種書寫順序,則即使得到signal,
//那麼無法獲得互斥鎖控制權,那麼將阻塞在lock上,相當於回退2行到 pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex); //內部先解互斥鎖才睡眠,等喚醒後自動加回互斥鎖。
}
//... do something here, queue.get() ... or use & delete something
count --;
pthread_mutex_lock(&mutex);//解互斥鎖
}轉載請註明出處,謝謝: http://blog.csdn.net/sprintfwater/article/details/21190859