Heim > Fragen und Antworten > Hauptteil
linux多线程编程手册有这样一段代码.我认为加上必要的主程序后,程序会在pthread_cond_wait(&count_nonzero, &count_lock)
处死锁.当count == 0
时阻塞同时没有解锁,则运行increment_count
的线程无法获得互斥锁,程序死锁.
然而,实际运行发现一切正常,请问是不是我哪里理解错了?请多多指教
pthread_mutex_t count_lock;
pthread_cond_t count_nonzero;
unsigned count;
decrement_count()
{
pthread_mutex_lock(&count_lock);
while(count == 0)
pthread_cond_wait(&count_nonzero, &count_lock);
count = count - 1;
pthread_mutex_unlock(&count_lock);
}
increment_count()
{
pthread_mutex_lock(&count_lock);
if(count == 0)
pthread_cond_signal(&count_nonzero);
count = count + 1;
pthread_mutex_unlock(&count_lock);
}
迷茫2017-04-17 13:14:53
因为pthread_cond_wait
函数内部会把count_lock
互斥量unlock
, 所以increment_count
可以lock
成功.