runtime
376 / 500
question 376 Threading & Multiprocessing · medium

Fix the transfer that can deadlock

Store-credit transfers lock both accounts. Occasionally the server freezes: one thread runs transfer(a, b, …) while another runs transfer(b, a, …); each holds one lock and waits forever for the other. Fix transfer so locks are always taken in the same global order (by account ID), whatever the direction.

Read and diagnose: this can't run in the browser, so you'll read real code and output and answer questions about it.

Functiontransfer(source, target, amount); each account is a dictionary with "id", "balance" and "lock"
Effectmoves amount from source to target while holding both locks; returns True, or False without changes if the source has too little
Rulealways acquire the lock of the account with the smaller id first

Loading your progress…

Fix the transfer that can deadlock — Python practice · Runtime