T11T1: lock(A)2T2: lock(B)3T1: lock(B)4T2: lock(A)LOCK BLOCK AT3T2
Pucks: threads · Boxes: locks, one dot per copySolid arrow: lock → thread, held · Dashed arrow: thread → lock, waitingTokens: a key granted, a request turned back, a tracer round the cycleThreads are round pucks, locks are boxes with one dot per copy. A solid arrow from a lock to a thread means the thread holds it; a dashed arrow from a thread to a lock means it waits for it. T1 holds A and waits for B while T2 holds B and waits for A: the arrows close a loop, a deadlock. When B has a second copy held by T3, the same loop breaks as soon as T3 finishes. Textbooks draw both kinds of arrow as plain solid arrows; the direction alone tells them apart. The figure dashes request arrows to make the waiting easier to see.

Drawing the graph

  1. A resource allocation graph is a picture of who holds what and who waits for what. Threads are circles. Resources, here two locks, are boxes, with one dot for each copy. Locks A and B have one copy each.

Reading a cycle

More than one copy

What happens

;; step 1/10 · symbols
thread      a circle         T1, T2
resource    a box            lock A, lock B
copy        a dot in a box   one copy each (a lock is one copy)

arrows (directed edges) come next:
  resource -> thread   assignment: the thread holds a copy
  thread -> resource   request: the thread waits for a copy

Textbooks draw both kinds of arrow as plain solid arrows; the direction alone tells them apart. The figure dashes request arrows to make the waiting easier to see. The card shortens pthread_mutex_lock(&A) to lock(A) and shows the four calls in the order they happen. In the whole program, T1 and T2 each sleep for a second after their first lock, so this order is almost certain; without the sleep the threads might not deadlock on a given run.