As we learned in the last post that in order for deadlocks to appear all of the necessary conditions must hold true at the same time and for preventing deadlocks we only need to stop one condition from occuring in the first place. We can prevent deadlocks from occuring by ensuring atleast one of the following condition does not occur.
Mutual Exclusion
The mutual Exclusion condition must hold true as only one process can have access to a resource. For example only one process can have access to the printer at the same time, otherwise the output will disrupt.
Some resources can be shareable like read-only files etc but deadlocks cannot be prevented by not limiting mutual exclusion because some resources are non-shareable.
Hold And Wait
To not letting Hold and Wait condition to occur we must ensure that when a process ask for access to some resource it does not have any other process in its access.
Another way to do this to only give the process all the resources only when they are available freely. But this can cause other problems. For example the process when granted access to all the resources at the same time may not need it for a lot of work but will keep it until it completes it execution which will reduce resource utilization.
No Prememption
The third way to prevent deadlocks is to prevent No Preemption condition from occuring.
One way to do this is that when a process wants to have access to some resource that is not available, all of the resources that that process is holding should be taken from him to give them to some other process until the resource's access it requested is granted to him.
But this approach only works if the resources are preemptimble. For example if a process is printing some text on paper using the printer and needs access to some other resource, the printer cannot be preempted in this case as it will disrupt the output on the paper.
Circular Wait
We can prevent deadlock by making Circular Wait impossible by defining an order by which the process get access to a resource. For example each resource is assigned a number and processes can only have access to the resource in increasing order of the number assigned to them.
For example we assign the memory as No: 1
and printer as No: 2
and a process wants to print something on paper using printer by reading some file from the memory first. It can do so by first accessing the memory file and then the printer and not the other way.
This way too have its own downsides as we can sometime assign numbers to resource in wrong order which can cause the process to slow down or completely stop. So to handle this we always number input resource before the output resources.