https://computing.llnl.gov/tutorials/pthreads/
Routines:
pthread_mutex_init (mutex,attr)
pthread_mutex_destroy (mutex)
pthread_mutexattr_init (attr)
pthread_mutexattr_destroy (attr)
Usage :
Mutex variables must be declared with type pthread_mutex_t, and must be initialized before they can be used. There are two ways to initialize a mutex variable:
1. Statically, when it is declared. For example:
pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;
2. Dynamically, with the pthread_mutex_init() routine. This method permits setting mutex object attributes, attr.
The mutex is initially unlocked.
# The attr object is used to establish properties for the mutex object, and must be of type pthread_mutexattr_t if used (may be specified as NULL to accept defaults). The Pthreads standard defines three optional mutex
attributes:
* Protocol: Specifies the protocol used to prevent priority inversions for a mutex.
* Prioceiling: Specifies the priority ceiling of a mutex.
* Process-shared: Specifies the process sharing of a mutex.
Note that not all implementations may provide the three optional mutex attributes.
# The pthread_mutexattr_init() and pthread_mutexattr_destroy() routines are used to create and destroy mutex attribute objects respectively.
# pthread_mutex_destroy() should be used to free a mutex object which is no longer needed.
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:
o If the mutex was already unlocked
o If the mutex is owned by another thread
Question: When more than one thread is waiting for a locked mutex, which thread will be granted the lock first after it is released?
Answer : Unless thread priority scheduling(not covered) is used, the assignment will be left to the native system scheduler and appear to be more or less random.