I'm trying to learn the difference between mutexes and conditional variables and am confused by the following code.
// Lock mutex and then wait for signal to relase mutex
pthread_mutex_lock( &count_mutex );
/*Wait while functionCount2() operates on count
mutex unlocked if condition varialbe in functionCount2() signaled. <-- so then why call pthread_mutex_unlock() 3 lines latter if it's already unlocked?*/
pthread_cond_wait( &condition_var, &count_mutex );
count++;
printf("Counter value functionCount1: %d\n",count);
pthread_mutex_unlock( &count_mutex );
According to the docs pthread_cond_wait()
"atomically release mutex and cause the calling thread to block on the condition variable" so what's the point of pthread_mutex_lock( &count_mutex );
if pthread_cond_wait()
just unlocks it and what's the point to the latter call pthread_mutex_unlock() since pthread_cond_wait()
had already unlocked it?
To me it would make sense if pthread_cond_wait() did not take a mutex, and I thought that was its point.