5

This question from elements of programming interviews claims there is a deadlock in the following code in the scenario where "U1 initiates a transfer to U2 and immediately afterwards U2 initiates a transfer to U1. Since each transfer takes place in a separate thread its possible for the first thread to lock U1 and then the second to lock U2"

class Account:
    _global_id = 0

    def __init__(self, balance):
        self._balance = balance
        self._id = Account._global_id
        Account._global_id += 1
        self._lock = threading.RLock()

    def get_balance(self):
        return self._balance

    @staticmethod
    def transfer(acc_from, acc_to, amount):
        th = threading.Thread(target=acc_from._move, args=(acc_to, amount))
        th.start()

    def _move(self, acc_to, amount):
        with self._lock:
            if amount > self._balance:
                return False
            acc_to._balance += amount
            self._balance -= amount
            print('returning True')
            return True

I do not see how there is a deadlock in that case. U1 and U2 have separate locks and as far as I can tell, thread1 just locks U1 and thread2 locks U2 since the _move method just uses self._lock and doesn't touch acc_to._lock. What am I missing?

3
  • Are you sure you copied the right example? I don't know that book, but I've seen books like it where there will be multiple examples for one problem. E.g., "...example A doesn't deadlock, but it also doesn't..., so we try to fix it by adding another lock as in example B, now it ..., but now it can deadlock." Sep 8, 2018 at 16:39
  • A typical deadlock in this kind of examples occurs when two threads are trying to get same two locks but in different order. But this is clearly NOT that case.
    – VPfB
    Sep 8, 2018 at 17:10
  • 1
    I was confused by this as well. I think the deadlock scenario would only make sense if acc_to._balance += amount was guarded by a with acc_to._lock statement, but I'd be curious if we're missing something.
    – Kevin Qi
    Jan 9, 2020 at 23:43

1 Answer 1

0

I had the same doubt and did not find a known error on the book's website. Based on the explanation of deadlock in the section before this problem, I think it should be

def _move(self, acc_to, amount):
        with self._lock, acc_to._lock:

instead of

def _move(self, acc_to, amount):
        with self._lock:

since that's the primary way deadlock will occur.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

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