In this link here, in the increment function, condition variable is signalled before actually incrementing the count(from zero). Should the signal be not invoked after incrementing the count? Or does the wait call in decrement_count function not return until the mutex is released in increment_function?
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);
}
Because of the mutex locks, it doesn’t matter if you do it before or after the signal, because the variable cannot be read until the mutex is unlocked.