title: Solution to Deadlock: Lock Ordering
body: <p>In the following code a deadlock is possible if two threads simultaneously invoke the <code>transaction()</code> function, transposing different accounts.</p>
  
  <pre><code>void transaction(Account from, Account to, double amount)
  {
        mutex lock1, lock2;
        lock1 = getlock(from);
        lock2 = getlock(to);
  
        acquire(lock1);
        acquire(lock2);
           withdraw(from, amount);
           deposit(to, amount);
        release(lock2);
        release(lock1);
  }
  </code></pre>
  
  <p>That is, one thread might invoke</p>
  
  <pre><code>transaction(checkingaccount, savingsaccount, 25);
  </code></pre>
  
  <p>and another might invoke</p>
  
  <pre><code>transaction(savingsaccount, checkingaccount, 50);
  </code></pre>
  
  <p>What is a good solution to this problem?</p>
  
  <p>One I can think of is to use a witness program that will alert the user that a deadlock has occurred, but there must be a better solution implementable by modifying the code. Any ideas?</p>
  
  <p>PS: This is from a textbook on operating systems.  This is not homework, just part of the chapter on deadlocks.</p>