In multitasking system and multiple processes running at the same time over number of resources sometimes we end up into a situation where each process starts waiting for a resource currently held by other resource and none of them in a position to let go off the resources held by them until the claimed resource is allocated to them. Pretty confusing? Yes, it is to some extent so we will first explain why a deadlock occurs. Lets say we have two processes P1 and P2 running parallely and there are two resources R1 and R2. Now both P1 and P2 start a transaction of their own and claim the two resouces in the following manner -
For Session 1 running P1 -
Step 1 - P1 claims R1 in shared mode
Step 2 - P1 wants to claim R2 in Exclusive mode
For Session 2 running P2 -
Step 1 - P2 claims R2 in shared mode
Step 2 - P2 wants to claim R1 in Exclusive mode
Now in the above situation if P1 or P2 runs both of their steps before the other process gets the CPU cycle then there wont be a deadlock however if in case when P1 completes step 1 and P2 starts executing Step 1 then both of the processes will each have a shared lock on separate resources. Now if again process P1 executes Step 2 then P1 will end up waiting for the resource R2 as exclusive mode is incompatible with the shared mode and same will happen with process P2. However, when process P2 will try to have exclusive mode right on the resource R1, system will enter into a deadlock situation and hence one of them will be detected by the system as deadlock victim and will be rolled back with the appropriate message.
For Session 1 running P1 -
Step 1 - P1 claims R1 in shared mode
Step 2 - P1 wants to claim R2 in Exclusive mode
For Session 2 running P2 -
Step 1 - P2 claims R2 in shared mode
Step 2 - P2 wants to claim R1 in Exclusive mode
Now in the above situation if P1 or P2 runs both of their steps before the other process gets the CPU cycle then there wont be a deadlock however if in case when P1 completes step 1 and P2 starts executing Step 1 then both of the processes will each have a shared lock on separate resources. Now if again process P1 executes Step 2 then P1 will end up waiting for the resource R2 as exclusive mode is incompatible with the shared mode and same will happen with process P2. However, when process P2 will try to have exclusive mode right on the resource R1, system will enter into a deadlock situation and hence one of them will be detected by the system as deadlock victim and will be rolled back with the appropriate message.