찾다

 >  Q&A  >  본문

linux - 多线程编程中有关条件变量的疑惑

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);
}
迷茫迷茫2788일 전784

모든 응답(1)나는 대답할 것이다

  • 迷茫

    迷茫2017-04-17 13:14:53

    因为pthread_cond_wait函数内部会把count_lock互斥量unlock, 所以increment_count可以lock成功.

    회신하다
    0
  • 취소회신하다