The symptom and three explanations#
A fictional invoice-worker stopped answering its health check at 03:12 UTC. The process was still running, its memory was flat, and its logs had stopped mid-batch. Before the orchestrator restarted it, the on-call engineer had three explanations:
- Deadlock. Two threads each hold a lock the other needs, and every request that touches either lock queues behind them.
- A busy loop or livelock. A thread is stuck in a loop waiting for a condition that never becomes true, or threads keep retrying against each other without either finishing.
- Blocked I/O. A thread is waiting on a read from a socket, pipe or network filesystem with no timeout, and the other end will never answer.
The health check, the logs and the memory graph predict the same thing for all three. Restarting clears all three as well and destroys the evidence, so read the process before the restart if the outage allows a minute.
What each explanation predicts#
| Observation | Deadlock | Busy loop or livelock | Blocked I/O |
|---|---|---|---|
| Process alive, no responses | yes | yes | yes |
| CPU of the stuck threads over a few seconds | none | about one core per spinning thread | none |
Thread state in /proc/PID/task/TID/stat | S | R, or switching between R and S | S, or D for disk and some network filesystems |
Wait channel (wchan) | a futex wait | 0, or a short wait that keeps changing | a socket, pipe or filesystem function |
| Stack, in two dumps a few seconds apart | the same, at lock acquisition, in a cycle | the same loop | the same read or receive call |
CPU and state separate the busy loop from the other two in seconds. The wait channel and the stack then separate a lock wait from an I/O wait, and the stack shows whether the lock waits form a cycle.
The lab: three ways to hang#
The first script hangs in the way you choose. In deadlock mode two threads take two locks in opposite order. In spin mode a thread loops on a flag that nothing sets. In io mode a thread reads from a pipe that nothing writes to. It registers faulthandler so that kill -USR1 prints every thread's Python stack without stopping the process. faulthandler
import faulthandler, os, signal, sys, threading, time
if len(sys.argv) < 2 or sys.argv[1] not in ("deadlock", "spin", "io"):
sys.exit("usage: python3 hang.py deadlock|spin|io")
mode = sys.argv[1]
faulthandler.register(signal.SIGUSR1) # kill -USR1 PID prints every thread's Python stack
a, b = threading.Lock(), threading.Lock()
def transfer(first, second): # two threads take the same two locks in opposite order
with first:
time.sleep(0.1)
with second:
pass
def spin(): # waits for a flag that nothing will ever set
done = False
while not done:
pass
def read_reply(): # waits for bytes that nobody will write
r, w = os.pipe()
os.read(r, 1)
if mode == "deadlock":
workers = [threading.Thread(target=transfer, args=(a, b)), threading.Thread(target=transfer, args=(b, a))]
elif mode == "spin":
workers = [threading.Thread(target=spin)]
else:
workers = [threading.Thread(target=read_reply)]
for t in workers:
t.daemon = True
t.start()
print(os.getpid(), flush=True)
time.sleep(30)
The second script reads, for every thread of a process, the state and the CPU ticks used over two seconds from /proc/PID/task/TID/stat, and the wait channel from /proc/PID/task/TID/wchan. In stat, field 3 is the state, and fields 14 and 15 are user and kernel CPU time in clock ticks; wchan holds "the symbolic name corresponding to the location in the kernel where the process is sleeping". Each thread has its own subdirectory under task/. proc_pid_stat(5) · proc_pid_wchan(5) · proc_pid_task(5)
#!/bin/bash
# usage: threads.sh PID prints state, CPU ticks used in 2 s and wait channel for every thread
pid=$1
snap() {
for t in /proc/"$pid"/task/*; do
# The thread name can contain spaces and closing parentheses.
stat=$(cat "$t/stat") || continue
read -ra fields <<< "${stat##*) }"
printf '%s %s %s %s\n' "${t##*/}" "${fields[0]}" "${fields[11]}" "${fields[12]}"
done
}
before=$(snap); sleep 2; after=$(snap)
join <(echo "$before") <(echo "$after") | while read -r tid s1 u1 k1 s2 u2 k2; do
printf '%-7s state %s CPU ticks in 2 s %4d wchan %s\n' "$tid" "$s2" $((u2 + k2 - u1 - k1)) "$(cat /proc/"$pid"/task/"$tid"/wchan)"
done
Save them as hang.py and threads.sh (chmod +x threads.sh). Write down, for each mode, the state, CPU and wait channel you expect for the worker threads. Then run each mode:
for m in deadlock spin io; do
python3 hang.py "$m" > pid.txt & sleep 1
echo "== $m"; ./threads.sh "$(cat pid.txt)"; kill %1; wait
done
On Linux 6.18 with Python 3.11 it printed (the clock tick is 100 per second here, so 200 ticks in 2 s is one full core):
== deadlock
27452 state S CPU ticks in 2 s 0 wchan hrtimer_nanosleep
27454 state S CPU ticks in 2 s 0 wchan futex_do_wait
27455 state S CPU ticks in 2 s 0 wchan futex_do_wait
== spin
27474 state S CPU ticks in 2 s 0 wchan hrtimer_nanosleep
27476 state R CPU ticks in 2 s 200 wchan 0
== io
27492 state S CPU ticks in 2 s 0 wchan hrtimer_nanosleep
27494 state S CPU ticks in 2 s 0 wchan anon_pipe_read
The first line of each block is the main thread in time.sleep. In deadlock mode both workers sleep in a futex wait with no CPU. In spin mode the worker is running and used a whole core (200 ticks). In io mode the worker sleeps in a pipe read. The prediction fails if the spinning thread shows S with no CPU, or the deadlocked threads use CPU. Thread IDs change on every run, and kernel function names change between kernel versions, so another kernel may show a different name for the same futex wait.
Then dump the deadlocked process's Python stacks:
python3 hang.py deadlock > pid.txt 2> stacks.txt & sleep 1
kill -USR1 "$(cat pid.txt)"; sleep 0.5; kill %1; cat stacks.txt
It printed (with the lab directory shortened to ...):
Thread 0x00007fa37bfff6c0 (most recent call first):
File ".../hang.py", line 12 in transfer
File "/usr/lib/python3.11/threading.py", line 982 in run
File "/usr/lib/python3.11/threading.py", line 1045 in _bootstrap_inner
File "/usr/lib/python3.11/threading.py", line 1002 in _bootstrap
Thread 0x00007fa380aff6c0 (most recent call first):
File ".../hang.py", line 12 in transfer
File "/usr/lib/python3.11/threading.py", line 982 in run
File "/usr/lib/python3.11/threading.py", line 1045 in _bootstrap_inner
File "/usr/lib/python3.11/threading.py", line 1002 in _bootstrap
Current thread 0x00007fa380ffd080 (most recent call first):
File ".../hang.py", line 34 in <module>
Line 12 is with second:. Each thread passed line 10, so each holds its first lock, and their arguments are (a, b) and (b, a): a cycle.
Read it on a real system#
These reads change nothing in the process.
top -H -p PID # live CPU per thread
ps -L -o tid,stat,wchan:32,comm -p PID # state and wait channel per thread
cat /proc/PID/task/*/stack # kernel stack per thread, as root
top -H shows individual threads instead of a sum per process. top(1) ps -L shows threads, and its wchan column is the "name of the kernel function in which the process is sleeping". Avoid ps's %cpu for this question: it is CPU time divided by the time the process has been running, so a thread that started spinning a minute ago in a day-old process shows a small number. ps(1) /proc/PID/stack gives the kernel stack only on kernels built with CONFIG_STACKTRACE, and needs ptrace access. proc_pid_stack(5)
For the application stacks, take two dumps a few seconds apart. On the JVM, jstack -l PID prints the stack traces of Java threads, and -l adds information about locks. jstack In Python, the faulthandler signal handler as in the lab, if the code registered it. In Go, a program linked with net/http/pprof serves goroutine stacks at /debug/pprof/goroutine?debug=2. net/http/pprof Sending SIGQUIT to a Go program also prints the stacks, but it makes the program exit, so it is a restart with a dump attached. os/signal
If the threads are waiting for a pool rather than for each other, and the service is slow rather than stopped, the question is a different one. Latency is high and CPU is low
Limits#
A deadlock and a wait on a slow lock holder look the same in one sample: both are threads asleep in a futex. Only the stacks show whether the waits form a cycle, and only a second dump shows whether anything moved.
A livelock can keep threads switching between R and S, with CPU well below a full core per thread, so it can look like ordinary load. Two dumps whose stacks are always in the same retry loop, with no work completed between them, identify it.
Blocked I/O on a network filesystem or a failing disk can leave threads in state D, uninterruptible disk sleep. A dump that relies on a signal may get no answer from those threads, so read their kernel stacks instead. A deadlock that involves a lock held by a thread waiting on I/O is both explanations at once, and the holder's stack decides which to fix first. For the method behind the table, see Choose the observation where explanations disagree.
Questions#
How do I tell a deadlock from an infinite loop on Linux?
Read each thread's CPU over a few seconds with top -H -p PID, or from fields 14 and 15 of /proc/PID/task/TID/stat. A thread in an infinite loop uses a full core and shows state R. Deadlocked threads use none and sleep in a futex wait.
What does the wchan column mean?
It is the name of the kernel function where a sleeping thread is waiting, such as a futex wait for a lock or a pipe or socket read for I/O. A running thread shows 0 or -. The function names vary between kernel versions, so read them as a category, not an exact string.
Should I restart a hung service before collecting evidence?
If users are affected and a restart is fast, restart. If you can spare a minute, take the thread states and two stack dumps first; they take seconds and are the only record of which explanation was true once the process is gone.