I am trying to get familiar with pthread library. Right now I am reading about condition variables (pthread_cond_t) and so I have a question about how does it work.
I found some sources with a simple example with usage of a pthread_cond_t struct (answer here https://stackoverflow.com/a/525841/3008684 and example 4-8 there https://docs.oracle.com/cd/E19455-01/806-5257/6je9h032r/index.html). it looks like this:
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);
}
As you can see in both methods is used the same count_lock object. My question is why it will not lead to a deadlock? Imagine a simple situation:
- count equals to zero
- decrement_count is called and now count_lock is locked
- count_lock will be unlocked if count is greater then zero
- increment_lock is called but blocked as count_lock is locked at the moment
- deadlock ???
Thanks in advance for any explanations!