Deadlocks, rwlocks & atomics
Prevent deadlocks with lock ordering and choose rwlocks or atomics when they fit.
By Invicly Tech, , in Linux System Programming. About 12 minutes to read.
In short
A deadlock happens when threads each hold a lock and wait for one another, so none can continue. It needs four conditions at once: mutual exclusion, hold and wait, no preemption and circular wait. A single global lock order breaks circular wait, and read-write locks or atomics reduce locking where they fit.
Explained simply
A deadlock is a traffic jam that never clears. Thread 1 holds lock A and waits for lock B. Thread 2 holds lock B and waits for lock A. Each waits for the other, forever. The program does not crash; it just stops doing anything, which is often harder to notice.
The good news: deadlocks follow simple rules. The most useful one is to always take locks in the same order everywhere. If every thread takes A before B, the circle of waiting can never form.
Not every shared value needs a full mutex. If many threads read data and only a few write it, a read-write lock lets the readers work at the same time. For a single counter or flag, C11 atomics do the job with no lock at all.
When a program does hang, a debugger shows exactly where each thread is stuck, so you can see which locks form the circle.
Press Play on a diagram to walk through it one step at a time.
- Thread 1 to Mutex A: lock(A) succeeds1lock(A) succeeds
- Thread 2 to Mutex B: lock(B) succeeds2lock(B) succeeds
- Thread 1 to Mutex B: lock(B) blocks: held by Thread 23lock(B) blocks: held by Thread 2
- Thread 2 to Mutex A: lock(A) blocks: held by Thread 14lock(A) blocks: held by Thread 1
- Protects any amount of data
- One thread at a time
- Cheap when uncontended
- The default choice
- Many readers or one writer
- Higher cost per operation
- Wins when reads dominate and sections are long
- glibc default can starve writers
- One variable only
- No lock, no blocking
- Counters, flags, pointers
- Cannot keep two fields consistent
In depth
The four conditions, and how to break each
Computer scientists (Coffman, 1971) showed that a deadlock needs four things at the same time. Mutual exclusion: a resource can be held by only one thread. Hold and wait: a thread keeps what it has while it waits for more. No preemption: nobody can take a lock away from its holder. Circular wait: there is a cycle of threads, each waiting for the next.
Remove any one and deadlock is impossible. In practice you break circular wait with lock ordering, which costs almost nothing. You break hold and wait by taking all needed locks up front, or with trylock and back off. Mutual exclusion is broken by not locking at all (atomics, immutable data, one owner thread per piece of data). Preemption is rarely practical for locks, though databases do it by aborting one transaction.
- Mutual exclusion
- Use atomics or immutable data
- Give data to one owner thread
- Hold and wait
- Take all locks at once
- trylock, release, retry
- No preemption
- Abort and retry, as databases do
- Circular wait
- One global lock order
- The cheapest and most common fix
Lock ordering in real code
With fixed locks, write the order down: for example config_lock before cache_lock before stats_lock, and never the reverse. Some teams give each lock a level number and assert in debug builds that levels only go up.
The hard case is two objects of the same type, like moving money between two accounts. transfer(a, b) locks a then b, while transfer(b, a) locks b then a: a deadlock waiting to happen. The fix is to order by something stable and unique, such as an account ID or the memory address of the objects. Always lock the lower one first, whichever is the source.
Also watch for hidden locks. Calling a callback, a logging function or any library code while holding your lock may take another lock you cannot see, and create a cycle.
- Document the order next to the lock declarations
- Same-type objects: lock the lower ID or address first
- Do not call unknown code while holding a lock
Debugging a hung program
If a process uses 0% CPU and stops responding, suspect a deadlock. Attach gdb with gdb -p PID, then run thread apply all bt. Threads stuck on a mutex show frames like __lll_lock_wait or futex_wait under pthread_mutex_lock, followed by your function and line. On glibc you can print the mutex in gdb (print lock) and read its __owner field, which holds the thread ID of the current owner. Follow owner to waiter to owner and you find the cycle.
Better still, catch ordering bugs before they hang. ThreadSanitizer reports lock-order-inversion (potential deadlock) when it sees two locks taken in both orders, even if the run did not actually deadlock. valgrind --tool=helgrind reports similar lock order violations.
- 1Process hangs at 0% CPU
Check with top or ps
- 2gdb -p PID
Attach to the live process
- 3thread apply all bt
Find threads inside pthread_mutex_lock
- 4print the mutex
__owner gives the holder's TID
- 5Follow the cycle
Fix the order, then test with TSan
Read-write locks for read-heavy data
A pthread_rwlock_t lets many readers hold the lock together, or one writer alone. Readers call pthread_rwlock_rdlock, writers call pthread_rwlock_wrlock, and both release with pthread_rwlock_unlock. It suits data that is read constantly and changed rarely, such as a routing table or loaded configuration.
Two cautions. First, a rwlock is more expensive than a mutex, because even readers update a shared counter. If the critical section is only a few instructions, a plain mutex is usually faster; measure before switching. Second, glibc's default rwlock prefers readers, so a steady stream of readers can starve a writer forever. If writers must make progress, set PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP with pthread_rwlockattr_setkind_np (a GNU extension). A reader must never try to upgrade to a writer while holding the read lock; two readers doing that deadlock each other.
C11 atomics for simple counters and flags
For one integer or pointer, C11 atomics from stdatomic.h avoid locks completely. Declare atomic_long hits; and call atomic_fetch_add(&hits, 1). The CPU performs the read, add and write as one indivisible instruction, so no update is lost. A stop flag can be an atomic_bool that the main thread sets and workers read.
By default every atomic operation uses sequentially consistent ordering, the strongest and simplest model. For a pure statistics counter, atomic_fetch_add_explicit(&hits, 1, memory_order_relaxed) is enough and slightly cheaper. atomic_compare_exchange_strong lets you build lock-free updates, but this gets subtle fast.
The limit is important: atomics protect one variable at a time. If two fields must change together (head and count of a queue, balance in two accounts), you still need a mutex.
- atomic_long n = 0; atomic_fetch_add(&n, 1);
- atomic_load and atomic_store for flags
- Several variables that must agree still need a mutex
Learn it in 5 short steps
About 40m each. Track them with a timer in your plan.
- 1Name the four deadlock conditions~40m
- 2Prevent deadlock with lock ordering~40m
- 3Debug a hung program with gdb thread apply~40m
- 4Use read-write locks for read-heavy data~40m
- 5Use C11 atomics for simple counters~40m
Key points
- Acquire multiple locks in one fixed global order everywhere.
- In gdb, thread apply all bt shows which lock each thread is waiting on.
- pthread_mutex_trylock lets you back off instead of blocking forever.
- Read-write locks allow many readers or one writer at a time.
- C11 atomics from stdatomic.h handle simple counters and flags without a mutex.
Key terms
Tap a card to flip it. 0/6 known
Examples
gdb -p $(pidof server)
(gdb) info threads
(gdb) thread apply all bt
# look for two threads stuck inside pthread_mutex_lock
valgrind --tool=helgrind ./server # reports lock order violationsFind out who holds what in a hung process.
A deadlock-free money transfer
Each account has its own mutex. A naive transfer locks from then to, so transfer(a, b) and transfer(b, a) running together deadlock. Step 1: pick a stable, unique order: the account ID. Step 2: always lock the account with the lower ID first, whichever direction the money moves. Step 3: refuse a transfer from an account to itself, because locking the same default mutex twice also hangs. Step 4: check the balance and move the money while both locks are held, then unlock both.
#include <pthread.h>
struct account { int id; long balance; pthread_mutex_t m; };
int transfer(struct account *from, struct account *to, long amount) {
if (from == to) return -1;
struct account *first = from->id < to->id ? from : to;
struct account *second = from->id < to->id ? to : from;
pthread_mutex_lock(&first->m);
pthread_mutex_lock(&second->m);
int ok = from->balance >= amount;
if (ok) { from->balance -= amount; to->balance += amount; }
pthread_mutex_unlock(&second->m);
pthread_mutex_unlock(&first->m);
return ok ? 0 : -1;
}A read-mostly config with an atomic hit counter
A server's request threads read the configuration on every request, and an admin command reloads it rarely. Step 1: guard the config pointer with a rwlock so request threads read in parallel. Step 2: the reload builds the new config without any lock, then takes the write lock only to swap the pointer. Step 3: the old config is freed after unlock. This is only safe because readers copy what they need before releasing the read lock and never keep the pointer. Step 4: count requests with an atomic, which needs no lock at all.
#include <pthread.h>
#include <stdatomic.h>
#include <stdlib.h>
static struct config { int max_clients; } *cfg; /* loaded at startup */
static pthread_rwlock_t cfg_lock = PTHREAD_RWLOCK_INITIALIZER;
static atomic_long requests;
int get_max_clients(void) {
atomic_fetch_add_explicit(&requests, 1, memory_order_relaxed);
pthread_rwlock_rdlock(&cfg_lock);
int v = cfg->max_clients; /* copy out, do not keep the pointer */
pthread_rwlock_unlock(&cfg_lock);
return v; }
void reload(struct config *fresh) { /* fresh was built without locks */
pthread_rwlock_wrlock(&cfg_lock); struct config *old = cfg; cfg = fresh;
pthread_rwlock_unlock(&cfg_lock); free(old); }Quick reference
- Deadlock needs: mutual exclusion, hold and wait, no preemption, circular wait
- Fix order once: always lock lower ID or address first
- gdb -p PID, then thread apply all bt: look for __lll_lock_wait
- In gdb, print mymutex shows __owner = TID of the thread holding it
- TSan reports lock-order-inversion before a real deadlock happens
- pthread_rwlock_rdlock / wrlock / unlock: many readers or one writer
- atomic_fetch_add(&n, 1) from stdatomic.h: lock-free counter
- pthread_mutex_trylock returns EBUSY instead of blocking
Common mistakes
- Calling a callback or unknown code while holding a lock.
- Locking a non-recursive mutex twice from the same thread.
Quick quiz
Pick an answer to see if you're right and why.
Practice exercises
Try each one yourself first. Use the hint if you get stuck, then compare with the solution.
- Exercise 1easy
Replace a mutex-protected request counter with a C11 atomic, and check that 4 threads doing 1 million increments each give exactly 4000000.
- Exercise 2medium
Write a program that deadlocks on purpose with two mutexes and two threads (add a short sleep between the locks). Attach gdb and find which thread waits on which lock.
- Exercise 3hard
Fix the deadlock above without a global lock order: use pthread_mutex_trylock for the second lock and back off with a random short delay on failure. Explain why it can still waste time.
Check yourself
Answer in your head, reveal, then be honest with yourself.
Feel confident about this topic?
Frequently asked questions
- How do I know if my program is deadlocked or just slow?
- A deadlocked process usually sits at 0% CPU with threads blocked inside pthread_mutex_lock. Attach gdb and run thread apply all bt; if the same backtraces stay the same over several samples, it is stuck.
- Can a single thread deadlock itself?
- Yes. Locking a default (non-recursive) mutex it already holds blocks forever. Calling a non-async-signal-safe function like malloc or printf from a signal handler can also deadlock on an internal lock.
- Is it safe to call fork in a multithreaded program?
- Only the calling thread is copied into the child, but locks held by other threads stay locked there forever. After fork in a threaded program, call only async-signal-safe functions and exec soon.
- What is a livelock?
- Threads keep running but make no progress, for example by repeatedly backing off and retrying at the same moment. Random back-off delays or a strict lock order prevent it.