The banker
An operating system can avoid deadlock the way a careful banker lends money. Each thread states up front its maximum: the most units of a resource it could ever hold. The banker lends a unit only if everyone can still finish.
Here 12 units exist. T0 holds 5 of its maximum 10, T1 holds 2 of 4, T2 holds 2 of 9. So 3 units are free. What each might still ask for is its need: maximum minus held, so 5, 2 and 7.
The safety check
A state is safe if there is some order in which every thread can get its whole need, finish, and give all its units back. To check, the banker plays the loans out in its head, starting from the free units.
Free is 3. T0 needs 5, too many, but T1 needs only 2. Pretend T1 gets them, finishes, and returns all 4 of its units: free becomes 3 − 2 + 4 = 5.
Now free is 5 and T0 needs 5, just enough. Pretend T0 gets them, finishes and returns all 10 of its units, so free becomes 10.
T2 needs 7 and 10 are free, so T2 can finish too, and all 12 units are back. The order T1, T0, T2 works, so the state is safe. None of this really happened: it was only a check.
Granting requests
Back to the real loans. T2 asks for 1 more unit. Before lending, the banker pretends to grant it: free drops to 2, T2 holds 3 and still needs 6. Then it runs the same check.
With 2 free, only T1 fits: it finishes and returns 4, so free is 4. Now T0 needs 5 and T2 needs 6. Neither fits, and no order is left. This state would be unsafe.
So the banker says not yet: the unit stays in the bank and T2 waits. Unsafe is not deadlock yet. T1 could still finish, but then T0 and T2 could each wait forever for units the other holds.
Later T1 asks for 1 unit. Pretend: free 2, T1 holds 3 and needs 1. T1 can finish (free 5), then T0 (free 10), then T2. Safe, so the banker lends the unit right away.
It works, but every thread must state its maximum in advance, and every request triggers a full check. General-purpose kernels such as Linux skip it and keep locks in a fixed order instead. The banker suits small, fixed systems.
What happens
;; step 1/11 · banker
deadlock threads wait for each other forever
prevention make a cycle impossible (e.g. lock order)
avoidance allow cycles in principle, but refuse any
loan that could lead into one
the banker needs, for every thread:
max the most units it may ever hold (stated up front)
has the units it holds now
Textbooks often call the banker's scratch copy of the free units Work, and the units held Allocation. The figure moves real-looking coins during the check, but the check only changes the copy: the real loans never move until a request is granted. The lesson uses one kind of resource, as in Dijkstra's original banker. With several kinds (say, printers and buffers), max, has, need and free become lists with one number per kind, and a thread fits only if its need is no bigger than free for every kind.