Mutex
A mutex is a lock that only one thread can hold at a time. Code between lock and unlock is a critical section: other threads that want the same mutex wait.
Detailed Explanation
pthread_mutex_t is the POSIX mutex. Initialize it with PTHREAD_MUTEX_INITIALIZER for a static mutex, or pthread_mutex_init for one you allocate. pthread_mutex_lock acquires it, blocking if another thread holds it. pthread_mutex_unlock releases it. Destroy it with pthread_mutex_destroy when no thread holds it and no thread is waiting.
The mutex does not know what data it protects. You do. The convention is: every read and write of a shared object happens while holding the mutex that owns that object. A comment on the mutex listing the fields is the documentation. A field touched both inside and outside the lock is a data race even if "it is only a flag."
Default mutexes are not recursive. Locking a mutex you already hold deadlocks on a normal POSIX mutex (or is undefined, depending on type). Recursive mutexes exist (PTHREAD_MUTEX_RECURSIVE) and hide design problems: you no longer know whether you are the first locker. Prefer a clear owner and no re-entry.
Unlock from the same thread that locked. Unlocking a mutex you do not hold is undefined. Unlocking in a different thread is undefined. A thread that dies while holding a mutex leaves it locked forever unless you used robustness attributes, which most programs do not.
C11 _Atomic and mutexes solve different problems. Atomics are for single words with a memory-order story. A mutex is for an invariant that spans several fields: "the length matches the allocated buffer." Do not replace a mutex with a volatile flag.
Hold the lock for a short time. Do not call unknown functions, blocking I/O, or printf to a contended stream while holding it if you can avoid it. Long critical sections serialize the program.
Code Examples
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t mu = PTHREAD_MUTEX_INITIALIZER;
static int counter;
static void *add(void *arg)
{
int n = *(int *)arg;
for (int i = 0; i < n; i++) {
pthread_mutex_lock(&mu);
counter++;
pthread_mutex_unlock(&mu);
}
return NULL;
}
int main(void)
{
int n = 100000;
pthread_t a, b;
pthread_create(&a, NULL, add, &n);
pthread_create(&b, NULL, add, &n);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("%d\n", counter); /* prints: 200000 */
return 0;
}Common Gotchas
Accessing the protected data without the lock is a data race
the program is undefined, not "eventually consistent."
A default mutex locked twice by the same thread deadlocks
do not re-enter; restructure the functions.
Forgetting `unlock` on an error path holds the lock forever
use a single unlock site or a cleanup helper.
`volatile` is not a mutex
it does not provide mutual exclusion or acquire/release on its own.