search

Home  >  Q&A  >  body text

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);
}
迷茫迷茫2837 days ago826

reply all(1)I'll reply

  • 迷茫

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

    Because the pthread_cond_wait function internally stores the count_lock mutex unlock, so increment_count can lock succeed.

    reply
    0
  • Cancelreply