<!DOCTYPE qhelp PUBLIC
  "-//Semmle//qhelp//EN"
  "qhelp.dtd">
<qhelp>

<overview>
<p>
Deadlock can occur when two or more threads each attempt to lock
multiple mutexes, but not in the same order.  A famous example of this
is the "Dining Philosophers Problem" (see references below). In this
example, deadlock occurs when all five philosophers simultaneously
pick up the fork to their left because then none of them can pick up
the fork to their right. A simple solution is to assign an order to
the mutexes. If the philosophers always pick up the lower numbered
fork first, rather than the fork to their left, then deadlock cannot
occur.
</p>

<p>
In general, we can build a graph of the order in which the mutexes are
locked. For example, if one of the threads locks mutex A first and B
second (while A is still locked), then we add a graph edge from A to
B. If the resulting graph contains a cycle then there is a possibility
of deadlock. The graph for the dining philosophers example contains a
cycle because each philosopher creates a graph edge from their left
fork to their right fork.
</p>
</overview>

<recommendation>
<p>
If multiple mutexes need to be locked simultaneously, then make sure
that all threads lock them in the same order.
</p>
</recommendation>

<example>

<p>
In this example, <code>f1</code> locks <code>mtx1</code> first and
<code>mtx2</code> second, but <code>f2</code> locks them in the
opposite order. If <code>f1</code> and <code>f2</code> are run
simultaneously in separate threads then they could cause a deadlock.
</p>

<sample src="LockOrderCycleExample.cpp" />

</example>
<references>

<li>Dijkstra, E. W., <i>EWD-310:
<a href="http://www.cs.utexas.edu/users/EWD/ewd03xx/EWD310.PDF">Hierarchical
Ordering of Sequential Processes</a></i>.  E. W. Dijkstra
Archive. Center for American History, University of Texas at Austin.
</li>

<li>Hoare, C. A. R.,
<i><a href="http://www.usingcsp.com/cspbook.pdf">Communicating
Sequential Processes</a></i>,
Section 2.5 - 'Example: The Dining Philosophers,' p. 55,
2004 (originally published in 1985 by Prentice Hall International).</li>

</references>
</qhelp>
