The pthread_mutex_unlock()
function shall release the mutex object referenced by mutex. But, the manner in which a mutex is released is dependent upon the mutex's type attribute. If there are threads blocked on the mutex object referenced by mutex when pthread_mutex_unlock()
is called, resulting in the mutex becoming available, the scheduling policy shall determine which thread shall acquire the mutex.
If the mutex type is PTHREAD_MUTEX_NORMAL
, deadlock detection shall not be provided. Attempting to relock the mutex causes deadlock. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, undefined behavior results.
If the mutex type is PTHREAD_MUTEX_ERRORCHECK
, then error checking shall be provided. If a thread attempts to relock a mutex that it has already locked, an error shall be returned. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, an error shall be returned.
If the mutex type is PTHREAD_MUTEX_RECURSIVE
, then the mutex shall maintain the concept of a lock count. When a thread successfully acquires a mutex for the first time, the lock count shall be set to one. Every time a thread relocks this mutex, the lock count shall be incremented by one. Each time the thread unlocks the mutex, the lock count shall be decremented by one. When the lock count reaches zero, the mutex shall become available for other threads to acquire. If a thread attempts to unlock a mutex that it has not locked or a mutex which is unlocked, an error shall be returned.
If the mutex type is PTHREAD_MUTEX_DEFAULT
, attempting to recursively lock the mutex results in undefined behavior. Attempting to unlock the mutex if it was not locked by the calling thread results in undefined behavior. Attempting to unlock the mutex if it is not locked results in undefined behavior.
I usually prefer to use PTHREAD_MUTEX_RECURSIVE
mutexes, because in this case the mutex shall become available when the count reaches zero and the calling thread no longer has any locks on this mutex.
pthread_mutex_unlock()
call above the call topthread_cond_signal()
. There's no requirement to hold the mutex while signaling the condition variable (only when waiting on it), and I suspect that what happens is that the signal causes contention on the mutex because the thread that gets released immediately attempts to acquire the mutex, which the signaling thread still holds. – Tunelessnon_empty
andnon_full
. Though one can't be 100% sure without seeing all of the code manipulating the shared resource, assuming that this is a standard use of the condition variables the change should be safe. Of course, assumptions can be dangerous (particularly with threading); I suppose that could have been mentioned, but honestly I didn't think of it. – Tuneless