Deadlock
Deadlock is a standstill where each thread waits for a resource another waiting thread holds. Nobody can make progress. The usual C form is two mutexes locked in opposite orders.
Detailed Explanation
Four conditions, all required: exclusive ownership, hold-and-wait, no preemption of locks, and a circular wait. Break any one and the deadlock is gone. In practice you break the circle: every thread acquires mutexes in the same global order. If you must lock A and B, everyone locks A first.
Self-deadlock is locking a non-recursive mutex you already hold. The thread waits for itself. That shows up when foo_locked calls bar which calls foo. Split the functions into an internal _locked version that assumes the mutex is held, and an external version that locks then calls _locked.
A deadlock can involve more than mutexes. A thread holds a mutex and waits on a condvar that will be signaled by a thread that needs the same mutex — but cond_wait releases the mutex, so that shape is fine. A thread holds a mutex and joins another thread that needs the mutex — that shape is not fine. A thread holds a mutex and allocates, and the allocator waits on a lock the first thread's partner holds.
Detection in development is a timeout plus logging who holds what, or tools that track lock graphs. Recovery in a C process is rarely graceful; you design not to deadlock. Robust mutexes can recover a lock after a crash, not after a live circle.
Livelock is the cousin: threads keep changing state and never finish (two people stepping aside forever). It is not deadlock, and the fix is backoff or a total order, not "more signaling."
Lock-free atomics can still livelock (CAS storms) but they do not deadlock on a mutex. They can starve. Pick the problem you are willing to have.
Code Examples
#include <pthread.h>
#include <stdio.h>
static pthread_mutex_t a = PTHREAD_MUTEX_INITIALIZER;
static pthread_mutex_t b = PTHREAD_MUTEX_INITIALIZER;
/* Safe: both threads lock a, then b. */
static void *work(void *arg)
{
(void)arg;
pthread_mutex_lock(&a);
pthread_mutex_lock(&b);
printf("got both\n");
pthread_mutex_unlock(&b);
pthread_mutex_unlock(&a);
return NULL;
}
int main(void)
{
pthread_t t1, t2;
pthread_create(&t1, NULL, work, NULL);
pthread_create(&t2, NULL, work, NULL);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}Common Gotchas
Locking the same non-recursive mutex twice in one thread deadlocks immediately
keep a `_locked` inner function.
Opposite lock orders (`A then B` vs `B then A`) deadlock under the right timing
sort mutexes by address if you have no better order.
`pthread_join` while holding a mutex the joinee needs is a deadlock
unlock first, or restructure ownership.
More locks make deadlock more likely
prefer one mutex for one invariant, or atomics for a single word.