CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Pthreads functions to manage mutexes

Creating and destroying:

Mutex variables must be declared with type pthread_mutex_t, and be initialized before being used. A mutex is initially unlocked. There are two ways to initialize a mutex variable:

  1. statically, when declared. e.g. pthread_mutex_t mymutex = PTHREAD_MUTEX_INITIALIZER;

  2. dynamically, with pthread_mutex_init(), which permits setting detailed mutex object attributes (the protocol used to prevent priority inversions, the priority ceiling of a mutex, and how mutexes may be shared).

pthread_mutex_destroy() may be used when a mutex object which is no longer needed (or, like dynamic memory, will be deallocated when the whole process terminates).

Locking and unlocking:

The pthread_mutex_lock() function acquires 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 function may be useful in preventing deadlock conditions.

pthread_mutex_unlock() will unlock a mutex if called by the owning thread, after it has completed its use of 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, they are just an agreement between participating threads. It is up to the programmer to ensure that all necessary threads make the mutex lock and unlock calls correctly.

 


CITS2002 Systems Programming, Lecture 21, p4, 10th October 2023.