linux - 多线程编程中有关条件变量的疑惑
迷茫
迷茫 2017-04-17 13:12:53
0
1
779

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

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
迷茫

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template