The pthread_mutex_lock() routine is used by a thread to acquire a lock on the specified mutex variable. If the mutex is already locked by another thread, this call will block the calling thread until the mutex is unlocked.
pthread_mutex_trylock() will attempt to lock a mutex. However, if the mutex is already locked, the routine will return immediately with a “busy” error code. This routine may be useful in preventing deadlock conditions, as in a priority-inversion situation.
pthread_mutex_unlock() will unlock a mutex if called by the owning thread. Calling this routine is required after a thread has completed its use of protected data if other threads are to acquire the mutex for their work with the protected data. An error will be returned if:
If the mutex was already unlocked
If the mutex is owned by another thread
There is nothing “magical” about mutexes…in fact they are akin to a “gentlemen’s agreement” between participating threads. It is up to the code writer to ensure that the necessary threads all make the the mutex lock and unlock calls correctly. The following scenario demonstrates a logical error:
Thread 1 Lock A = 2 Unlock
Thread 2 Lock A = A+1 Unlock
Thread 3 A = A*B
Question: When more than one thread is waiting for a locked mutex, which thread will be granted the lock first after it is released?
Click for answer.
Unless thread priority scheduling (not covered) is used, the assignment will be left to the native system scheduler and may appear to be more or less random.
Lawrence Livermore National Laboratory
7000 East Avenue • Livermore, CA 94550 | LLNL-WEB-458451
Operated by the Lawrence Livermore National Security, LLC for the
Department of Energy's National Nuclear Security Administration
Learn about the Department of Energy's Vulnerability Disclosure Program