Skip to content
Advertisement

Do we need to unlocking a mutex after recived a signal from cond variable?

I making an app in C for educational purposes with mutexes and conditional variables.

Short example here:

while (!(is_done == 0))         
    pthread_cond_wait(&cond, &mutex);

 pthread_mutex_unlock(&mutex); 

Can you explain me, why after “while” statment (and recived signal from second thread) we need to unlock the mutex, when signal makes that mutex is locked?

I get it from a lot examples from web, but when i want to work with mutex after reciving signal, do i need to unlocking mutex? Ofc i want to work on this thread after reciving signal

Advertisement

Answer

Can you explain me, why after “while” statment (and recived signal from second thread) we need to unlock the mutex, when signal makes that mutex is locked?

When pthread_cond_wait returns the mutex is locked so that you can examine the shared state protected by it safely:

These functions 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.

Upon successful return, the mutex shall have been locked and shall be owned by the calling thread. If mutex is a robust mutex where an owner terminated while holding the lock and the state is recoverable, the mutex shall be acquired even though the function returns an error code.

Generally, a mutex should be unlocked as soon as possible to reduce contention.

In your case, you wait for shared state is_done to change. Once it changed and you are done accessing the shared state protected by the mutex, the mutex must be unlocked.

Advertisement