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 insure that the necessary threads all make the the mutex lock and unlock calls correctly. The following scenario demonstrates a logical error:
Question: When more than one thread is waiting for a locked mutex, which thread will be granted the lock first after it is released?