Part 2 of 7 · 2 min read
The mutex
In plain words: A key hangs on a hook beside a single shared toolbox. Whoever takes the key may open the toolbox, and must hang the key back when finished. If the key is gone, a person who needs the toolbox waits. The analogy stops in one place: a person can see who holds the key, and a thread cannot tell which thread holds a mutex without asking the library.
A mutex (short for mutual exclusion) is a lock that at most one thread can hold at a time. A thread locks it before entering a critical section and unlocks it afterwards. A thread that tries to lock a mutex that another thread holds waits until it is free. Only the thread that locked a mutex may unlock it.
The POSIX calls are:
| Call | Job |
|---|---|
pthread_mutex_init(&m, attr) or PTHREAD_MUTEX_INITIALIZER |
Create a mutex (the macro suits a static one) |
pthread_mutex_lock(&m) |
Take the lock, and wait if it is held |
pthread_mutex_trylock(&m) |
Take the lock if it is free, and return EBUSY at once if not |
pthread_mutex_unlock(&m) |
Release the lock |
pthread_mutex_destroy(&m) |
Free the mutex when it is no longer used |
All of them return 0 on success and an error number on failure (Level 2, page 2). Here is the counter of Level 2, page 4, as the model of use:
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
static long counter;
pthread_mutex_lock(&mu);
counter++; /* the critical section */
pthread_mutex_unlock(&mu);
The rule that makes it correct: every access to the shared data, reading as well as writing, is made while holding the same mutex. One access without the lock is a race, whatever the other accesses do. The mutex does not know what it protects. The programmer decides, and a comment next to the data saying "protected by mu" is good practice.
pthread_mutex_trylock returns at once. A test where thread A holds the mutex and thread B tries:
other thread: trylock returned 16 (Device or resource busy) <- while the main thread holds it
other thread: trylock returned 0 (got it) <- after the main thread released it
Mutex
A mutex is a synchronisation object that can be held by at most one thread at a time: a thread that locks it gains exclusive entry to a critical section, other threads that try to lock it wait, and only the holder may unlock it.
Example: pthread_mutex_lock(&mu) returns when the calling thread owns mu; until it calls pthread_mutex_unlock(&mu), every other thread that locks mu waits.
Check yourself:
1. What does pthread_mutex_trylock return when the mutex is held?
2. Why must every access to the data, including reads, take the lock?
3. Who may unlock a mutex?