Part 4 of 8 · 2 min read
All at once
In plain words: Hold and wait means a thread holds one resource while it asks for another. There are two ways to remove it. The first is to ask for everything at the start: a thread that needs accounts a and b takes both, as one step, before it does any work. The second is to hold nothing while asking: if a thread needs another resource, it first gives back all it holds, and then asks for the full set.
The simplest all-or-nothing method in a program is a single big lock. The transfer function takes one lock that covers all accounts, changes both balances, and releases it:
pthread_mutex_lock(&big);
acc[a].bal--; acc[b].bal++;
pthread_mutex_unlock(&big);
There is only one lock, so no thread ever holds one lock and waits for another, and a cycle cannot form. The cost is concurrency. Two transfers that touch different accounts could safely run together, but the big lock makes them take turns. Measured on the test machine, with random transfers among four accounts (three runs each, 2 s per run):
| Threads | One big lock |
|---|---|
| 2 | 7.1 to 7.4 million transfers per second |
| 4 | 8.5 to 11.2 million transfers per second |
The numbers are not far from the other methods in this case, because the critical section is only a few instructions long. The cost grows when the work inside the lock gets longer, since every thread waits for the one that holds it.
A second price is early knowledge. A thread must know all the resources it will need before it starts, which is often untrue. A batch job may open its second file only after reading the first. A third price is waste: a thread that asks for a tape drive and a plotter at the start keeps the plotter for the whole hour of its analysis, although it needs the plotter only at the end.
All-or-nothing acquisition
All-or-nothing acquisition is a rule that a thread obtains every resource it needs in a single step, or none of them, so that it never holds one resource while waiting for another.
Example: a transfer that takes one lock for the whole account table gets both accounts together, or waits holding nothing.
Check yourself: 1. Why can a single lock never take part in a deadlock cycle by itself? 2. What is the cost in concurrency of the big lock? 3. Why does asking for all resources at the start waste resources?