Bitpath

Boss lesson · Unit 02

The frozen transfer

Two locks, opposite orders, and the fix

13 exercisesabout 3 min

What you practise

  • Two locks taken in opposite orders, the four conditions for deadlock, fixing it with a global lock order, timeouts, starvation and livelock

Try a question from this lesson

Pick one

Each account has its own lock, and a transfer takes the sender's lock first. Two opposite transfers start together. What happens next?

thread 1: transfer a -> b
thread 2: transfer b -> a

T1 locks a          T2 locks b
T1 wants b: waits   T2 wants a: waits
Hint

For T1 to continue, T2 must release b. What does T2 need before it will do that?

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Deadlock

A deadlock is a cycle of waiting: each thread holds a lock that another one needs, and none lets go.

This transfer looks innocent. Run a → b and b → a at the same time and each thread can take its first lock, then wait forever for its second.

The program does not crash. It just stops.

Python
def transfer(src, dst, amount):
    with src.lock:
        with dst.lock:
            src.balance -= amount
            dst.balance += amount

Concept

Timeouts, livelock, starvation

When a global order is not possible, ask for the second lock with a timeout. If it runs out, release everything, wait a random moment and try again.

The random wait matters. Two threads that give up and retry in perfect step can repeat that dance forever: a livelock, busy but going nowhere.

Starvation is one thread never getting its turn because others always get in first.

10 more exercises in the app

  • 2× type the answer
  • 1× match the pairs
  • 3× multiple choice
  • 1× fill the blanks
  • 2× true or false
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy