Previous | Next --- Slide 30 of 64
Back to Lecture Thumbnails
PID_1

This slide shows one of the difficulties of programming with locks.

Any time a piece of code must acquire multiple locks to run, it needs to be the case that all other pieces of code that need those locks acquire them in the same order. Otherwise, if both pieces of code acquire at least one of those locks, they will deadlock waiting for the other to be released.

Defining a total ordering on locks and always acquiring in this order fixes this issue.

memebryant

@PID_1, note that this isn't always possible. For more information on writing deadlock-free code, see the OS lecture notes.

CaptainBlueBear

The deadlock would occur here if one thread acquires its first lock before the other is able to acquire its second. Then thread 0 will be waiting to acquire its second lock on account y which is being held by thread 1 and thread 1 will be waiting to acquire its second lock on account x which is held by thread 0

stride16

If thread 0 acquires the first lock, while thread 1 has yet to acquire the second lock, it will result in a deadlock. A deadlock could possibly avoided if both the threads had specified the locks in the same order.

captainFlint

This deadlock can be avoided by imposing a an standard order on the locks within the transfer function. For example, we can take max of A and B and always acquire the lock on the max of the two first and the min of the two second. This would prevent deadlock whilst also ensuring correctness of the function.