Operating System - Deadlock Prevention

 What is Deadlock?

A deadlock occurs when a group of processes are each waiting for a resource that another process in the group holds — and none of them can proceed.

Four Necessary Conditions for Deadlock

Deadlock can occur only if all four of these conditions are true simultaneously:

  1. Mutual Exclusion 

  2. Hold and Wait 

  3. No Preemption 

  4. Circular Wait 

Deadlock Prevention

Deadlock prevention means designing the system to prevent at least one of the above conditions from occurring.

 How to Prevent Deadlock

1. Mutual Exclusion – Not Preventable (Usually)

  • Some resources must be used exclusively (e.g., printers).

  • So, this condition is generally not preventable.

2. Hold and Wait – Preventable

Solution: Require processes to request all required resources at once, before starting.

Example:
Process A needs Printer and Scanner. It must request both at once, or release what it holds if it can't get the rest.

Downside:
Low resource utilization and possible starvation.

3. No Preemption – Preventable

Solution: If a process is waiting for a resource, take away all it holds and restart it later.

Example:
If Process B has a file and is waiting for a printer, the file is taken back and B is moved to a waiting state.

Downside:
Not practical for non-preemptible resources (like CPU execution state or printing half a document).

4. Circular Wait – Preventable

Solution: Impose a strict ordering on resource requests.

Example:

  • Number resources: R1 = 1, R2 = 2, R3 = 3, etc.

  • Processes must request resources in increasing order only.

So:

  • If a process has R1, it can request R2, but not R0.

Result: No circular wait can form.

To prevent deadlock:

  • Let all processes request both resources at once (break Hold and Wait).

  • Or, use resource ordering (e.g., always request Scanner before Printer).

Deadlock prevention means proactively designing systems so deadlocks can’t happen, even at the cost of performance or convenience. In real systems, prevention is often combined with detection and recovery or avoidance strategies.