Safety Algorithm example:
Beginning state:
A has 10 instances
B has 5 instances
C has07 instances

This algorithm works by comparing what resources the process needs to finish to what resources are currently available. For each process that can complete; the resources currently allocated to that process are added to the Resources Available vector and the processes entry in the Finish vector updated to True. If all entries in the Finish vector are true at completion of the algorithm then the system is in a safe state.

Assignment matrix
Process Resource alloc Resource Max Available
  A B C A B C A B C
p0 0 1 0 7 5 3 3 3 2
p1 2 0 0 3 2 2      
p2 3 0 2 9 0 2      
p3 2 1 1 2 2 2      
p4 0 0 2 4 3 3      
Need matrix
(Need[i,j] = Max[i,j] - Allocation[i,j])
Process Need
  A B C
p0 7 4 3
p1 1 2 2
p2 6 0 0
p3 0 1 1
p4 4 3 1



The finish order = p1, p3, p4, p0, p2 and our finish table shows all process finished (finish[x] = T). Note also that our finishing resource count (FR = (10, 5, 7)) equals our starting resource count (SR = (10, 5, 7)); a useful cross check, because if all processes have completed then all resources have been released.


Resource request check
1) Check request is < Need
2) Check request is < Available
3) Run Safety Algorithm on updated values; if it shows safe then grant request


p1 req(1, 0, 2)
p1 req(1, 0, 2) < need(1, 2, 2) == Ok
p1 req(1, 0, 2) < available(3, 3, 2) == Ok

p1 set_resource_alloc (2, 0, 0) + (1, 0, 2) = (3, 0, 2)
p1 set_resource_need (1, 2, 2) - (1, 0, 2) = (0, 2, 0)

Then run the safety algorithm on the values as found below. If passes; then the resource allocation succeeds. If it doesn't pass; then the allocation fails.
Test matrix values
Process Resource alloc Resource Max Available Needed resource
  A B C A B C A B C A B C
p0 0 1 0 7 5 3 2 3 0 7 4 3
p1 3 0 2 3 2 2       0 2 0
p2 3 0 2 9 0 2       6 0 0
p3 2 1 1 2 2 2       0 1 1
p4 0 0 2 4 3 3       4 3 1


Deadlock detection:

resource A has 7 instances
resource B has 2 instances
resource C has 6 instances

The deadlock checking algorithm can be used to detect if deadlock exist. For each process, the algorithm checks whether or not it can met its resource request and thus allow the process to complete. If so; then its entry in the finish veector is marked true; false if otherwise. For each process marked true; its resources are added to the Resources Available vector and the next process requests are checked.

Starting condition
Process Resource alloc Resource request Resource Available
  A B C A B C A B C
p0 0 1 0 0 0 0 0 0 0
p1 2 0 0 2 0 2      
p2 3 0 3 0 0 0      
p3 2 1 1 1 0 0      
p4 0 0 2 0 0 2      

Deadlock checking