Code:
void *inc_func(void *arg)
{
pthread_mutex_lock(&mutex);
pthread_cond_signal(&count_threshold_cv);
sleep(1);
pthread_mutex_unlock(&mutex);
}
void *watch(void *arg)
{
pthread_mutex_lock(&mutex);
pthread_cond_wait(&count_threshold_cv,&mutex);
sleep(1);
pthread_mutex_unlock(&mutex);
}
int main()
{
pthread_t id[2];
pthread_create(&id[0],NULL,watch,NULL);
pthread_create(&id[1],NULL,inc_func,NULL);
int i;
for(i=0;i<2;i++)
pthread_join(id[i],NULL);
}
Now we have one mutex_unlock
function to be executed in each thread. And one locked mutex. Why doesn't this lead to an undefined behaviour
. Since both threads try to unlock the same mutex which leads to one trying to unlock an already unlocked mutex.
Edit: pthread_cond_wait
releases the mutex
for the second thread to use. Now consider the second thread executes pthread_cond_signal
which leads to the first thread to reacquire the mutex
. Now we have two threads having the same mutex
lock,because both didn't get to execute the mutex_unlock
because of the 'sleep' function. Is my understanding wrong?