Deadlock
I first learned about this when preparing for my AMD interview, as well as CS348. Taught in detail through SE350.
Deadlock can be defined as the permanent blocking of a set of processes that either compete for system resources or communicate with each other.
Three conditions of policy must be present for a deadlock to be possible:
Necessary Conditions
- Mutual exclusion. Only one process may use a resource at a time. No process may access a resource unit that has been allocated to another process.
- Hold and wait. A process may hold allocated resources while awaiting assignment of other resources.
- No Preemption. No resource can be forcibly removed from a process holding it.
Sufficient Conditions 4. Circular wait. A closed chain of processes exists, such that each process holds at least one resource needed by the next process in the chain
- Figure 6.5d has the same topology as Figure 6.5c, but there is no deadlock because multiple units of each resource are available.
Example
In the example (c) above, P1 requires resource Ra and is in possession of resource Rb. P2 requires additional resource Rb and is in possession of Ra; neither process can continue.
Dealing with Deadlocks
There are 3 approaches to deal with deadlocks:
Methods summary
How to avoid deadlocks in practice (software level)?
Avoid Nested Locks: This is the main reason for deadlock. Deadlock mainly happens when we give locks to multiple threads. Avoid giving locks to multiple threads if you already have given to one.
Avoid Unnecessary Locks: You should lock only those members which are required. Having unnecessary locks can lead to a deadlock. As a best practice, try to reduce the need to lock things as much as you can.