There are 3 rules for Safety Algorithm:
1. we calculate Available resources ( in a Matrix structure )
2. Need <=(less than and equal to) Available
3. Available = available + Allocation
so in this question our Allocation matrix and Need matrix are respectively:
A B A B
P0 2 1 P0 6 2
P1 1 2 P1 4 5
P2 0 2 P2 3 2
P3 1 0 P3 5 6
question says,
there are 4 units of each resource type is available , so our Available matrix becomes
A B
4 4
so start from P0 it have need 6,2 it not satisfy 4,4 which is available. Only P2 satisfy it has 3,2 so our new Available matrix become (4,4 + 0,2) = 4,6 so now P3 can not satisfy it. P0 also can not, P1 have 4,5 it can satisfy. so now our safe sequence is <P2 , P1> .
next Available become (4,6 + 1,2)= 5,8 so now P3 comes next , it can satisfy. new Available become 5,8 + 1,0= 6,8 now P0 can satisfy it . so final safe sequence become < P2 , P1. P3, P0 > .
Safe Sequence: < P2 ,P1 ,P3 ,P0 > so P0 will execute last.