Skip to content

银行家算法 ​

基础概念 ​

  • 当前可用资源数 Available
  • 已分配到的资源数 Allocation
  • 尚需资源需求 Need = Max - Allocation

例题 ​

进程已分配到的资源Allocation尚需资源需求Need当前可用资源数Available
P0(1,1,1,0)(0,3,3,1)(0,3,2,2)
P1(0,2,3,1)(0,3,4,2)
P2(0,2,1,2)(1,0,3,4)
P3(0,3,1,0)(0,3,2,0)
P4(1,0,2,1)(0,4,2,3)

该状态是否安全 ​

1. 画表格 ​

进程\资源WorkNeedAllocationWork+AllocationFinish

2. 写出 Work ​

第一个 Work 就是 Available。

进程\资源WorkNeedAllocationWork+AllocationFinish
0,3,2,2

3. 挑选 Need ​

若 Need < Work,就可以。刚好P3 可以,Need 为 (0,3,2,0)。

进程\资源WorkNeedAllocationWork+AllocationFinish
P30,3,2,20,3,2,00,3,1,00,6,3,2T

4. 写出下一个 Work ​

下一个 Work 就是上一个 Work+Allocation,所以就是 (0,6,3,2)。

进程\资源WorkNeedAllocationWork+AllocationFinish
P30,3,2,20,3,2,00,3,1,00,6,3,2T
0,6,3,2

5. 挑选 Need ​

发现 P0 就可以,是 (0,3,3,1)。然后找到对应的 Allocation,最终计算出 Work+Allocation。

进程\资源WorkNeedAllocationWork+AllocationFinish
P30,3,2,20,3,2,00,3,1,00,6,3,2T
P00,6,3,20,3,3,11,1,1,01,7,4,2T

6. 以此类推 ​

进程\资源WorkNeedAllocationWork+AllocationFinish
P30,3,2,20,3,2,00,3,1,00,6,3,2T
P00,6,3,20,3,3,11,1,1,01,7,4,2T
P11,7,4,20,3,4,20,2,3,11,9,7,3T
P41,9,7,30,4,3,21,0,2,12,9,9,4T
P22,9,9,41,0,3,40,2,1,22,11,10,6T

所以该状态安全。安全序列为 P3 → P0→ P1→ P4→ P2

如果 P0 提出资源请求 (0,0,0,1) 系统能否将资源分配给它 ​

回到题干 ​

进程已分配到的资源Allocation尚需资源需求Need当前可用资源数Available
P0(1,1,1,0)(0,3,3,1)(0,3,2,2)
P1(0,2,3,1)(0,3,4,2)
P2(0,2,1,2)(1,0,3,4)
P3(0,3,1,0)(0,3,2,0)
P4(1,0,2,1)(0,4,2,3)

判断是否可以更新 ​

此时判断 Request 是否都小于 Need 和 Available。

P0 时,Request = (0,0,0,1),此时 Need = (0,3,3,1),Available = (0,3,2,2)

由于:

Request < Need 且 Request < Available

所以可以更新。

开始更新 ​

  • 新的 Need' = Need - Request
  • 新的 Allocation' = Allocation + Request
  • 新的 Available' = Available - Request

更新后:

  • Need' = (0,3,3,0)
  • Allocation' = (1,1,1,1)
  • Avaliable' = (0,3,2,1)
进程已分配到的资源Allocation尚需资源需求Need当前可用资源数Available
P0(1,1,1,1)(0,3,3,0)(0,3,2,1)
P1(0,2,3,1)(0,3,4,2)
P2(0,2,1,2)(1,0,3,4)
P3(0,3,1,0)(0,3,2,0)
P4(1,0,2,1)(0,4,2,3)

判断安全性 ​

进程\资源WorkNeedAllocationWork+AllocationFinish
P30,3,2,10,3,2,00,3,1,00,6,3,1T
P00,6,3,10,3,3,01,1,1,11,7,4,2T
P11,7,4,20,3,4,20,2,3,11,9,7,3T
P41,9,7,30,4,2,31,0,2,12,9,9,4T
P22,9,9,41,0,3,40,2,1,22,11,10,6T

所以该状态安全。

安全序列为 P3 → P0→ P1→ P4→ P2