Operating Systems Module 5: Deadlock Lesson 5.2 14 min

Avoiding deadlock: lock ordering and the Banker’s algorithm

Prevention breaks one of the four conditions, and lock ordering is the practical way. Avoidance uses the Banker’s algorithm: grant a request only if the system stays in a safe state.

You now know what a deadlock needs: four conditions, all at once (Lesson 5.1). So the cheapest way to never have a deadlock is to make sure at least one condition can never be true. There are two families of cures. Prevention designs the system so that one condition is impossible. Avoidance lets all four be possible, but looks at every request and refuses the ones that could lead into trouble.

Prevention: break one condition

Take the four conditions in turn.

  • Mutual exclusion. Let the resource be shared. A read-only file needs no lock at all, and a printer can be shared by spooling: programs write into files, and one daemon prints them in turn. But a lock protecting a bank balance is mutual exclusion by definition, so this cure only works for some resources.
  • Hold and wait. Make a process ask for everything at once, or release what it holds before asking for more. It works, but resources sit idle while their owner waits for the rest, and a process that needs a popular resource can wait for ever.
  • No preemption. If a request cannot be met, make the process give up what it holds and start again. pthread_mutex_trylock lets a program do this by itself. It is awkward for locks, because the work done under them may be half finished.
  • Circular wait. Give every resource a number, and require that every process asks for resources in increasing order. A loop would need some process to ask for a lower number while holding a higher one, which is not allowed. This is lock ordering, and it is the cure programmers really use.

Lock ordering fixes the bank transfer

A bank moves money between accounts, and each account has its own lock. A transfer locks the source account, then the destination (the project in Lesson 4.6 builds this). Two transfers in opposite directions at the same moment are the two locks of the last lesson in disguise.

Two transfers in opposite directions, no ordering

  1. The processes and the resources Circles are processes and boxes are resources. The dots in a box are its instances: a hollow dot is free, a filled dot is held. Here 2 processs (T1, T2) will use acct1 and acct2.
    Cycle
    none
    Deadlock
    no
    Waiting
    nobody
    Free
    acct1 1/1, acct2 1/1
  2. T1 holds acct1 T1 is given acct1. The arrow runs from the resource to the process: it is assigned to T1, and nobody else can use that instance until T1 lets go.
    Cycle
    none
    Deadlock
    no
    Waiting
    nobody
    Free
    acct1 0/1, acct2 1/1
  3. T2 holds acct2 T2 is given acct2. The arrow runs from the resource to the process: it is assigned to T2, and nobody else can use that instance until T2 lets go.
    Cycle
    none
    Deadlock
    no
    Waiting
    nobody
    Free
    acct1 0/1, acct2 0/1
  4. T1 asks for acct2 T1 asks for acct2, but every instance is free. T1 must wait. The arrow runs from the process to the resource: it is a request, not yet an assignment.
    Cycle
    none
    Deadlock
    no
    Waiting
    T1
    Free
    acct1 0/1, acct2 0/1
  5. T2 asks for acct1 T2 asks for acct1, but every instance is free. T2 must wait. The arrow runs from the process to the resource: it is a request, not yet an assignment.
    Cycle
    T1 → acct2 → T2 → acct1 → T1
    Deadlock
    yes
    Waiting
    T1, T2
    Free
    acct1 0/1, acct2 0/1
  6. Search for a cycle Follow the arrows and you come back to where you started: T1 → acct2 → T2 → acct1 → T1. Every resource on it has one instance, so each process waits for something only the next one can give back. Nobody on the cycle can ever move: this is a deadlock.
    Cycle
    T1 → acct2 → T2 → acct1 → T1
    Deadlock
    yes
    Waiting
    T1, T2
    Free
    acct1 0/1, acct2 0/1
  7. Deadlock: T1 and T2 wait for ever T1 and T2 can never get what they ask for: each one needs something another of them holds, and none of them will let go. Only an outside action (killing one, or a timeout) can break this.
    Cycle
    T1 → acct2 → T2 → acct1 → T1
    Deadlock
    yes
    Waiting
    T1, T2
    Free
    acct1 0/1, acct2 0/1

The fix is one rule, written once, in the transfer function: always lock the account with the lower number first, whichever side is the source. T2, moving money from account 2 to account 1, now asks for account 1 before account 2.

The same two transfers, lowest account first

  1. The processes and the resources Circles are processes and boxes are resources. The dots in a box are its instances: a hollow dot is free, a filled dot is held. Here 2 processs (T1, T2) will use acct1 and acct2.
    Cycle
    none
    Deadlock
    no
    Waiting
    nobody
    Free
    acct1 1/1, acct2 1/1
  2. T1 holds acct1 T1 is given acct1. The arrow runs from the resource to the process: it is assigned to T1, and nobody else can use that instance until T1 lets go.
    Cycle
    none
    Deadlock
    no
    Waiting
    nobody
    Free
    acct1 0/1, acct2 1/1
  3. T2 asks for acct1 T2 asks for acct1, but every instance is free. T2 must wait. The arrow runs from the process to the resource: it is a request, not yet an assignment.
    Cycle
    none
    Deadlock
    no
    Waiting
    T2
    Free
    acct1 0/1, acct2 1/1
  4. T1 holds acct2 T1 is given acct2. The arrow runs from the resource to the process: it is assigned to T1, and nobody else can use that instance until T1 lets go.
    Cycle
    none
    Deadlock
    no
    Waiting
    T2
    Free
    acct1 0/1, acct2 0/1
  5. No cycle Follow the arrows from every node: you never get back to where you started. With no cycle there can be no deadlock, because somebody can always finish and let go.
    Cycle
    none
    Deadlock
    no
    Waiting
    T2
    Free
    acct1 0/1, acct2 0/1
  6. T1 can finish T1 needs nothing more. It runs to the end and releases acct1 and acct2, which may free somebody else.
    Cycle
    none
    Deadlock
    no
    Waiting
    nobody
    Free
    acct1 1/1, acct2 1/1
  7. T2 can finish T2 asks for acct1 and a free instance is there, so it gets it. It runs to the end and releases what it held, which may free somebody else.
    Cycle
    none
    Deadlock
    no
    Waiting
    nobody
    Free
    acct1 1/1, acct2 1/1
  8. No deadlock: everyone finishes Every process could finish, so the state is not deadlocked.
    Cycle
    none
    Deadlock
    no
    Waiting
    nobody
    Free
    acct1 1/1, acct2 1/1

T2 waits at the first lock. It holds nothing, so T1 can take its second lock, finish and release both, and T2 then runs. With the rule in place no loop can ever form: the program below is that rule in C, and two threads that move money in opposite directions 100 times each now always finish.

transfer.c
#include <pthread.h>
#include <stdio.h>

typedef struct { int id; int balance; pthread_mutex_t lock; } account;

account accounts[2] = {
    { 1, 1000, PTHREAD_MUTEX_INITIALIZER },
    { 2, 1000, PTHREAD_MUTEX_INITIALIZER },
};

void transfer(account *from, account *to, int amount) {
    account *first  = from->id < to->id ? from : to;    /* lower id first */
    account *second = from->id < to->id ? to : from;
    pthread_mutex_lock(&first->lock);
    pthread_mutex_lock(&second->lock);
    from->balance -= amount;
    to->balance   += amount;
    pthread_mutex_unlock(&second->lock);
    pthread_mutex_unlock(&first->lock);
}

void *forward(void *arg) {                               /* account 1 -> account 2 */
    for (int i = 0; i < 100; i++) transfer(&accounts[0], &accounts[1], 10);
    return NULL;
}

void *backward(void *arg) {                              /* account 2 -> account 1 */
    for (int i = 0; i < 100; i++) transfer(&accounts[1], &accounts[0], 10);
    return NULL;
}

int main(void) {
    pthread_t a, b;
    pthread_create(&a, NULL, forward, NULL);
    pthread_create(&b, NULL, backward, NULL);
    pthread_join(a, NULL);
    pthread_join(b, NULL);
    printf("account 1: %d, account 2: %d, total: %d\n",
           accounts[0].balance, accounts[1].balance, accounts[0].balance + accounts[1].balance);
    return 0;
}

Output (one run)

account 1: 1000, account 2: 1000, total: 2000

Lock ordering costs nothing at run time. Its weakness is that it needs discipline: every piece of code in the program, including a library written by someone else, must follow the same global order.

Avoidance: the Banker’s algorithm

Ordering does not help when the order in which a process needs resources cannot be known in advance. For that case there is avoidance. The best-known version is the Banker’s algorithm, named after a banker who lends to customers and never wants to be in a position where he cannot satisfy everybody.

Every process must declare in advance the maximum it will ever need of each resource. The table has these columns:

  • Allocation: what each process holds now.
  • Max: the most it will ever ask for.
  • Need = Max − Allocation: what it may still ask for.
  • Available: what is free right now. It is the total, minus everything allocated.

A state is safe if there is some order in which the processes can finish: a safe sequence. Each process in the order can get its whole Need from what is free plus what the earlier processes give back. To check it, set Work equal to Available. Find a process whose Need fits inside Work, let it finish, add its allocation to Work, and repeat. If everyone finishes, the state is safe.

These are invented numbers: three resources A, B and C, and four processes. Predict which process can go first.

Is this state safe?

  1. The state Each process has declared the most it will ever need (Max). Need = Max − Allocation, row by row. Available = Total − everything allocated = [1 1 2].
    Available
    [1 1 2]
    Work
    (not started)
    Request
    none
    Safe sequence so far
    none yet
  2. Start the safety search The question: can every process finish, one after another? Start with Work = Available = [1 1 2]. Look down the table for a process whose Need fits inside Work.
    Available
    [1 1 2]
    Work
    [1 1 2]
    Request
    none
    Safe sequence so far
    none yet
  3. P4 can finish P4 needs at most [1 0 2] more, and Work is [1 1 2], so it fits. Let P4 run to the end. It gives back its allocation [1 1 1], so Work becomes [2 2 3].
    Available
    [1 1 2]
    Work
    [2 2 3]
    Request
    none
    Safe sequence so far
    P4
  4. P2 can finish P2 needs at most [2 0 1] more, and Work is [2 2 3], so it fits. Let P2 run to the end. It gives back its allocation [2 0 1], so Work becomes [4 2 4].
    Available
    [1 1 2]
    Work
    [4 2 4]
    Request
    none
    Safe sequence so far
    P4 P2
  5. P1 can finish P1 needs at most [3 2 3] more, and Work is [4 2 4], so it fits. Let P1 run to the end. It gives back its allocation [2 1 1], so Work becomes [6 3 5].
    Available
    [1 1 2]
    Work
    [6 3 5]
    Request
    none
    Safe sequence so far
    P4 P2 P1
  6. P3 can finish P3 needs at most [1 3 3] more, and Work is [6 3 5], so it fits. Let P3 run to the end. It gives back its allocation [1 1 0], so Work becomes [7 4 5].
    Available
    [1 1 2]
    Work
    [7 4 5]
    Request
    none
    Safe sequence so far
    P4 P2 P1 P3
  7. Safe: P4 P2 P1 P3 Everyone could finish. The order P4, P2, P1, P3 is a safe sequence. A state with a safe sequence is a safe state: the system can always get everyone through.
    Available
    [1 1 2]
    Work
    [7 4 5]
    Request
    none
    Safe sequence so far
    P4 P2 P1 P3
    Decision
    safe

P4 finishes and gives its allocation back, which makes room for P2, then P1, then P3. So P4, P2, P1, P3 is a safe sequence, and the state is safe. There may be other safe sequences. The simulator scans from the top each time, so it reports the first one it finds. All that matters is that at least one exists.

A state that is not safe is called unsafe. Unsafe does not mean deadlocked: the processes might never ask for their maximum. It means the system has lost the guarantee, so it is one unlucky sequence of requests away from being stuck.

Granting a request

The Banker applies the safety test to every request. When a process asks for more, the Banker checks, in order:

  1. Is the request within the process’s Need? If not, the process is breaking its own promise.
  2. Is it within Available? If not, the process has to wait.
  3. Pretend to grant it. Is the new state still safe? If so, grant it. If not, refuse, put everything back, and make the process wait.

First, P4 asks for 0 0 2. Watch the pretend state: it is checked exactly like the table above.

P4 asks for 0 0 2

  1. The state Each process has declared the most it will ever need (Max). Need = Max − Allocation, row by row. Available = Total − everything allocated = [1 1 2].
    Available
    [1 1 2]
    Work
    (not started)
    Request
    none
    Safe sequence so far
    none yet
  2. P4 asks for [0 0 2] P4 requests [0 0 2] now. The Banker does not just hand it over: it checks three things, in order.
    Available
    [1 1 2]
    Work
    (not started)
    Request
    P4 [0 0 2]
    Safe sequence so far
    none yet
  3. Within its Need and within Available The request [0 0 2] fits inside P4's Need [1 0 2] and inside Available [1 1 2]. Having enough free is not the whole test. Next question: if we grant it, is the new state still safe?
    Available
    [1 1 2]
    Work
    (not started)
    Request
    P4 [0 0 2]
    Safe sequence so far
    none yet
  4. Pretend to grant it Do not grant it for real yet. Move [0 0 2] from Available to P4's allocation on paper: Allocation becomes [1 1 3], Need [1 0 0] and Available [1 1 0]. Now run the safety search on this pretend state.
    Available
    [1 1 0]
    Work
    (not started)
    Request
    P4 [0 0 2]
    Safe sequence so far
    none yet
  5. Start the safety search The question: can every process finish, one after another? Start with Work = Available = [1 1 0]. Look down the table for a process whose Need fits inside Work.
    Available
    [1 1 0]
    Work
    [1 1 0]
    Request
    none
    Safe sequence so far
    none yet
  6. P4 can finish P4 needs at most [1 0 0] more, and Work is [1 1 0], so it fits. Let P4 run to the end. It gives back its allocation [1 1 3], so Work becomes [2 2 3].
    Available
    [1 1 0]
    Work
    [2 2 3]
    Request
    none
    Safe sequence so far
    P4
  7. P2 can finish P2 needs at most [2 0 1] more, and Work is [2 2 3], so it fits. Let P2 run to the end. It gives back its allocation [2 0 1], so Work becomes [4 2 4].
    Available
    [1 1 0]
    Work
    [4 2 4]
    Request
    none
    Safe sequence so far
    P4 P2
  8. P1 can finish P1 needs at most [3 2 3] more, and Work is [4 2 4], so it fits. Let P1 run to the end. It gives back its allocation [2 1 1], so Work becomes [6 3 5].
    Available
    [1 1 0]
    Work
    [6 3 5]
    Request
    none
    Safe sequence so far
    P4 P2 P1
  9. P3 can finish P3 needs at most [1 3 3] more, and Work is [6 3 5], so it fits. Let P3 run to the end. It gives back its allocation [1 1 0], so Work becomes [7 4 5].
    Available
    [1 1 0]
    Work
    [7 4 5]
    Request
    none
    Safe sequence so far
    P4 P2 P1 P3
  10. Safe: P4 P2 P1 P3 Everyone could finish. The order P4, P2, P1, P3 is a safe sequence. A state with a safe sequence is a safe state: the system can always get everyone through.
    Available
    [1 1 0]
    Work
    [7 4 5]
    Request
    none
    Safe sequence so far
    P4 P2 P1 P3
    Decision
    safe
  11. Grant the request The pretend state is safe, so the request is granted for real. P4 now holds [1 1 3], and the safe sequence P4, P2, P1, P3 shows that everyone can still finish.
    Available
    [1 1 0]
    Work
    (not started)
    Request
    none
    Safe sequence so far
    P4 P2 P1 P3
    Decision
    grant

The pretend state has the same safe sequence, so the Banker grants the request. Now the same table, and the same request of 0 0 2, but made by P1 instead.

P1 asks for the same 0 0 2

  1. The state Each process has declared the most it will ever need (Max). Need = Max − Allocation, row by row. Available = Total − everything allocated = [1 1 2].
    Available
    [1 1 2]
    Work
    (not started)
    Request
    none
    Safe sequence so far
    none yet
  2. P1 asks for [0 0 2] P1 requests [0 0 2] now. The Banker does not just hand it over: it checks three things, in order.
    Available
    [1 1 2]
    Work
    (not started)
    Request
    P1 [0 0 2]
    Safe sequence so far
    none yet
  3. Within its Need and within Available The request [0 0 2] fits inside P1's Need [3 2 3] and inside Available [1 1 2]. Having enough free is not the whole test. Next question: if we grant it, is the new state still safe?
    Available
    [1 1 2]
    Work
    (not started)
    Request
    P1 [0 0 2]
    Safe sequence so far
    none yet
  4. Pretend to grant it Do not grant it for real yet. Move [0 0 2] from Available to P1's allocation on paper: Allocation becomes [2 1 3], Need [3 2 1] and Available [1 1 0]. Now run the safety search on this pretend state.
    Available
    [1 1 0]
    Work
    (not started)
    Request
    P1 [0 0 2]
    Safe sequence so far
    none yet
  5. Start the safety search The question: can every process finish, one after another? Start with Work = Available = [1 1 0]. Look down the table for a process whose Need fits inside Work.
    Available
    [1 1 0]
    Work
    [1 1 0]
    Request
    none
    Safe sequence so far
    none yet
  6. Unsafe: nobody else can finish With Work at [1 1 0], P1, P2, P3 and P4 each need more than that. No safe sequence exists, so the state is unsafe. Unsafe does not mean deadlocked yet, but the system can no longer promise to avoid it.
    Available
    [1 1 0]
    Work
    [1 1 0]
    Request
    none
    Safe sequence so far
    none yet
    Decision
    unsafe
  7. Refuse the request The pretend state is unsafe, so the Banker refuses and puts everything back as it was. P1 waits, even though [0 0 2] was free. Refusing now is how the Banker stays out of a state from which deadlock could not be avoided.
    Available
    [1 1 2]
    Work
    (not started)
    Request
    none
    Safe sequence so far
    none yet
    Decision
    refuse

The Banker refuses P1’s request. The 0 0 2 was free, it was within P1’s declared need, and nothing had gone wrong yet. But granting it would have left a state where no process could be sure to finish, so the request is refused and everything is put back as it was. P1 waits until something changes.

Now press Try it, switch it to the Banker’s table, and change the numbers: make the request smaller, give P1 a smaller maximum, or change the totals. Typing something impossible (a process holding more than its maximum, say) shows the error beside the box that caused it.

Why isn’t this in every operating system?

It is a beautiful algorithm, and almost nobody uses it for general-purpose systems. It asks for things the real world rarely provides:

  • Every process has to know its maximum in advance, and programs do not. A text editor cannot say how many files it will have open tomorrow.
  • The number of processes must be fixed and the resources too, but real systems start and stop processes all the time.
  • It must run on every request, and the safety search costs work in proportion to the processes and resources.
  • It is cautious: it holds back requests that would never in fact have deadlocked, which leaves resources idle.

So general-purpose operating systems leave deadlock to programmers (Lesson 5.3). The Banker’s idea still lives on in places where resources and maximum needs are known in advance, and it is the standard way to teach what a safe state is.

In the real world

The kernel’s lockdep tool (Lesson 5.1) is lock ordering made automatic. Every time the kernel code takes a lock, lockdep records which locks were already held. It builds a graph of “A was held while B was taken”, and when a new path would close a loop, it prints a warning, naming the two locks and the code that took them, long before a real deadlock hits.

Databases do something similar for rows, and some real-time and embedded systems use a Banker-like admission check, because there all the maximum needs are known when the system is designed.

Recap

  • Prevention makes one of the four conditions impossible. The practical cure is lock ordering: number the locks and always take them in increasing order, so a loop cannot form.
  • Avoidance lets a process ask for anything but checks each request. The Banker’s algorithm needs every process to declare its Max in advance.
  • A state is safe if some order, a safe sequence, lets every process finish. An unsafe state is not deadlocked yet, but the guarantee is gone.
  • The Banker grants a request only if it is within Need, within Available, and the state after granting is still safe. Otherwise it is refused even if the resources are free.
  • General-purpose systems rarely use it: processes do not know their maximum, and the checks cost time and leave resources idle.

Quick check

Quick check

  1. What is a safe state in the Banker's algorithm?
  2. The Banker has enough free resources to meet a request, yet it refuses. Why can that happen?
  3. Why is the Banker's algorithm rarely used in general-purpose operating systems?
  4. Every transfer locks the lower-numbered account first, whichever one is the source. Which deadlock condition does this rule remove?

Your progress is saved in this browser. Sign in to keep it on every device. Free, no password.

Join the discussion