Fork me on GitHub

Locking and Unlocking Mutexes

Routines:

pthread_mutex_lock (mutex)

pthread_mutex_trylock (mutex)

pthread_mutex_unlock (mutex)

Usage:

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:

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:


</br>

Thread 1
Lock
A = 2
Unlock
Thread 2
Lock
A = A+1
Unlock
Thread 3

A = A*B


</br>

Question: When more than one thread is waiting for a locked mutex, which thread will be granted the lock first after it is released?
</br>

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.