LogSeq/pages/Banker's Algorithm.md
2023-04-12 21:43:34 +08:00

1.8 KiB

  • Wiki Zhihu
  • It is usually quoted in EXAMs, thus still worth some time.
  • 3 matrices is indexed by [ProcessID, ResourceID]
    • Max: the maximum number of resources that will be needed during execution of each kind
    • Allocated: the number resources that is already allocated to the process
    • Need: the number of resources that the process still needs, i.e. Need = Max - Allocated
  • 2 vectors indexed by [ResourceID]
    • Total: the number of each kind of resources in the system
    • Available: the number of resources that is not yet allocated by the OS, i.e. Available = Total - sum(Allocated, axis=1)
  • Safe state: it is possible for all processes to finish executing. If we can find a possible sequence of execution, where the each process is able to acquire its maximum resources, and terminates.
  • Safe sequence algorithm
    • suppose we have a sequence of P1 P2 ... Pn
      1. start from the current state S[i] which is after execution of P[i-1]
      2. if Available >= Need[i, :] then P[i] is able to terminate; else it is not a safe sequence, return false
      3. after P[i] terminates, Available += Allocated[i, :] and i += 1, then loop back to 2 until all process is executed
  • Request
    • When the system receives a request for resources, it runs the Banker's algorithm to determine if it is safe to grant the request. The algorithm is fairly straightforward once the distinction between safe and unsafe states is understood.

      1. Can the request be granted? If not, the request is impossible and must either be denied or put on a waiting list
      2. Assume that the request is granted
      3. Is the new state safe? If so grant the request; If not, either deny the request or put it on a waiting list