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

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

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

membalas semua(1)
迷茫

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

Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan