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?
The pthread_mutex_lock() function acquires ownership of the mutex specified. If the mutex currently is locked by another thread, the call to pthread_mutex_lock() blocks until that thread relinquishes ownership by a call to pthread_mutex_unlock().
The function pthread_mutex_trylock is identical to pthread_mutex_lock except that if the robust mutex object referenced by the mutex parameter is currently locked (by any thread, including the current thread), the call returns immediately. The pthread_mutex_unlock function releases the mutex object referenced by mutex.
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.
pthread_mutex_lock() returns zero after completing successfully. Any other return value indicates that an error occurred. When any of the following conditions occurs, the function fails and returns the corresponding value.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With