1

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:

  1. count equals to zero
  2. decrement_count is called and now count_lock is locked
  3. count_lock will be unlocked if count is greater then zero
  4. increment_lock is called but blocked as count_lock is locked at the moment
  5. deadlock ???

Thanks in advance for any explanations!

Community
  • 1
  • 1
antonpp
  • 2,333
  • 23
  • 28
  • 1
    Look at the documentation for `pthread_conditions_wait`: *[This function] **atomically release mutex** and cause the calling thread to block on the condition variable cond; atomically here means "atomically with respect to access by another thread to the mutex and then the condition variable". That is, if another thread is able to acquire the mutex after the about-to-block thread has released it, then a subsequent call to pthread_cond_broadcast() or pthread_cond_signal() in that thread shall behave as if it were issued after the about-to-block thread has blocked.* – didierc Dec 08 '14 at 00:17

1 Answers1

0

The 1st google result for pthread_cond_wait explains that the function will release the lock on the mutex and automatically restore it once the condition has been signaled.

Grant Peters
  • 7,691
  • 3
  • 45
  • 57