Handling Deadlocks: Prevention
To prevent deadlocks, the OS could prevent one of the four necessary conditions for a deadlock:
- Mutual Exclusion: Unfortunately, this condition can't be prevented and must always hold to avoid race conditions. However, note that resources that can be shared by several processes, like read-only files, don't cause deadlocks.
- Hold and Wait: The OS must prevent processes from holding one or more resources while simultaneously waiting for one or more others. This could be done by requiring that processes holding resources release them before requesting new resources.
- No preemption: The OS must do the following: if a process is forced to wait when requesting a new resource, then all other resources previously held by this process are implicitly released (preempted), forcing this process to re-acquire the old resources along with the new resources in a single request, similar to the previous solution.
- Circular Wait: The OS must enumerate all the resources and then require that processes request resources only in strictly increasing (or decreasing) order. In other words, in order to request resource Rj, a process must first release all the resources {R0, R1, R2, ..., Rj-1} that it holds.