Simple Deadlock Examples

Roee Adler picture Roee Adler · Sep 6, 2009 · Viewed 135.8k times · Source

I would like to explain threading deadlocks to newbies. I have seen many examples for deadlocks in the past, some using code and some using illustrations (like the famous 4 cars). There are also classic easily-deadlocked problems like The Dining Philosophers, but these may be too complex for a real newbie to fully grasp.

I'm looking for the simplest code example to illustrate what deadlocks are. The example should:

  1. Relate to a "real" programming scenario that makes some sense
  2. Be very short, simple and straight forward

What do you recommend?

Answer

AAA picture AAA · Sep 6, 2009

Maybe a simple bank situation.

class Account {
  double balance;

  void withdraw(double amount){
     balance -= amount;
  } 

  void deposit(double amount){
     balance += amount;
  } 

   void transfer(Account from, Account to, double amount){
        sync(from);
        sync(to);

        from.withdraw(amount);
        to.deposit(amount);

        release(to);
        release(from);
    }

}

Obviously, should there be two threads which attempt to run transfer(a, b) and transfer(b, a) at the same time, then a deadlock is going to occur because they try to acquire the resources in reverse order.

This code is also great for looking at solutions to the deadlock as well. Hope this helps!