Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Threads trying to acquire pthread_mutex_lock(&mutex) What happens if they don't get the lock?

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?

like image 604
Bobby S Avatar asked Mar 11 '11 00:03

Bobby S


People also ask

What does pthread_mutex_lock mean?

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().

What is the difference between pthread_mutex_lock and pthread_mutex_trylock?

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.

Does pthread_mutex_lock block?

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.

What is the return value of pthread_mutex_lock?

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.


1 Answers

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.

like image 143
Carl Norum Avatar answered Oct 08 '22 13:10

Carl Norum