Andy Leung
Andy Leung

Reputation: 21

Preventing Deadlocks

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?

Upvotes: 2

Views: 1382

Answers (2)

JAB
JAB

Reputation: 21089

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.)

Upvotes: 2

Anders Abel
Anders Abel

Reputation: 69270

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.

Upvotes: 5

Related Questions