Step 1
Provide a natural ordering for your resources. For example, if your resources were letters, A
would come before B
, B
would come before C
, and so on.
Step 2
Only allow your threads to grab resources in order.
Now your threads cannot possibly reach deadlock in any situation.
Example
- Thread 1 needs locks on resources
A
,B
,D
, andE
- Thread 2 needs locks on resources
B
andE
Our threads must fight for locks on resources B
and D
. Because we have enforced a natural order, the thread that obtains the lock on B
first is guaranteed to get the lock on D
and proceed smoothly. The losing thread will be waiting for B
to be released.