2

for a pseudo function like

void transaction(Account from, Account to, double amount){
      Semaphore lock1, lock2;
      lock1 = getLock(from);
      lock2 = getLock(to)

      wait(lock1);
         wait(lock2);

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

         signal(lock2);
      signal(lock1);
}

deadlock happens if you run transaction(A,B,50) transaction(B,A,10)

how can this be prevented?

would this work?

2 Answers 2

5

A simple deadlock prevention strategy when handling locks is to have strict order on the locks in the application and always grab the locks according to this order. Assuming all accounts have a number, you could change your logic to always grab the lock for the account with the lowest account number first. Then grab the lock for the one with the highest number.

Another strategy for preventing deadlocks is to reduce the number of locks. In this case it might be better to have one lock that locks all accounts. It would definitely make the lock structure far more simple. If the application shows performance problems under heavy load and profiling shows that lock congestion is the problem - then it is time to invent a more fine grained locking strategy.

2
  • 1
    Thanks for your answer would: wait(lock1); withdraw(from, amount); signal(lock1); wait(lock2); withdraw(amount, from); signal(lock2); work?
    – Andy Leung
    Aug 8, 2011 at 20:30
  • 2
    Yes, the updated code in the question would work from a deadlock perspective. You won't hold both locks at the same time. For deposits/withdrawals it is usually important to have atomicity as well, which requires both locks though. Aug 8, 2011 at 20:34
2

By making the entire transaction a critical section? That's only one possible solution, at least.

I have a feeling this is homework of some sort, because it's very similar to the dining philosophers problem based on the example code you give. (Multiple solutions to the problem are available at the link provided, just so you know. Check them out if you want a better understanding of the concepts.)

1
  • I was thinking the exact same thing.
    – Perception
    Aug 8, 2011 at 20:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.