C Programming:
What happens when a thread tries to acquire a mutex lock, and fails to get it?
Does it go to sleep?
Will the thread be woken up when pthread_mutex_unlock(&mutex); is called?
Then try to obtain the lock again?
From the man page:
The
pthread_mutex_lock()
function locks mutex. If the mutex is already locked, the calling thread will block until the mutex becomes available.
So yes - your thread is blocked until the lock is available and it can obtain it.
Yes, it is a blocking call and will block until it gets the lock.
The non-blocking version is pthread_mutex_trylock(pthread_mutex_t *mutex)
and will return EBUSY
if someone else has the lock, or 0
if it got the lock. (Or some other error, of course)
Normally, pthread_mutex_lock
cannot return until it acquires the lock, even if this means that it never returns (deadlock). There are a few notable exceptions though:
EAGAIN
if the maximum reference count would be exceeded.EDEADLK
if the thread tries to lock a mutex it already holds a lock on.EOWNERDEAD
if another process died while holding the (shared) mutex. In this case, despite getting an error return, the caller holds the mutex lock and can mark the mutex-protected state valid again by calling pthread_mutex_consistent
.pthread_mutex_unlock
without calling pthread_mutex_consistent
first, it will return ENOTRECOVERABLE
.There may be a few cases I missed. Note that none of these apply to normal mutexes (PTHREAD_MUTEX_NORMAL
type) without the robust attribute set, so if you only use normal mutexes, you can reasonably assume the call never returns without succeeding.
From the POSIX standard:
If the mutex is already locked, the calling thread shall block until the mutex becomes available.
(...)
If there are threads blocked on the mutex object referenced by
mutex
whenpthread_mutex_unlock()
is called, resulting in the mutex becoming available, the scheduling policy shall determine which thread shall acquire the mutex.
Where the "resulting in" clause is necessary because
(In the case of
PTHREAD_MUTEX_RECURSIVE
mutexes, the mutex shall become available when the count reaches zero and the calling thread no longer has any locks on this mutex.)