銀行家算法是什麼
銀行家
主要就是通過放貸來賺錢的。那最重要的問題是啥?當然是把錢借給還得起的人咯。試想,銀行把錢都借給了還不起的人,那銀行就完蛋了。假設有一批人(多個進程)來借錢(將要申請資源),但是銀行剩下的錢滿足不了任何人,那就直接拒絕借貸。當然了,有一部分已經借出的錢回收之後(回收已經分配的資源),又可以滿足一批人中某些人的借貸需求。依次類推,銀行可以判定能不能按照某個順序來給這批人放貸。類似的思路延伸到計算機世界,同理。操作系統給多個進程分配資源,能不能找到一個順序給這些進程分配資源,並逐漸回收資源?
從而滿足多個進程的資源需求。採用銀行家放貸和收貸的思路(這裏排除利息,放多少貸,收多少錢。呵呵,哪有此種好事?)來分配和回收系統資源就是所謂的銀行家算法
。
銀行家算法解決什麼問題
resource allocation and deadlock avoidance algorithm
。銀行家算法用來進行資源分配和避免死鎖。
銀行家算法怎樣解決問題
P0、P1、P2、P3、P4 5個進程,視爲需要錢的 5 個人。A、B、C 三種系統資源。分別視爲是銀行三種貴金屬:金塊、銀塊、銅塊。
allocation table 已放貸表
每個人已經借的金銀銅個數列表
A | B | C | |
---|---|---|---|
P0 | 0 | 1 | 0 |
P1 | 2 | 0 | 0 |
P2 | 3 | 0 | 2 |
P3 | 2 | 1 | 1 |
P4 | 0 | 0 | 2 |
max table 最大借貸表
每個人需要金銀銅最大個數列表
A | B | C | |
---|---|---|---|
P0 | 7 | 5 | 3 |
P1 | 3 | 2 | 2 |
P2 | 9 | 0 | 2 |
P3 | 2 | 2 | 2 |
P4 | 4 | 3 | 3 |
need table 還需放貸表
每個人還需要的金銀銅個數列表。由 max table - allocation table 得到。
A | B | C | |
---|---|---|---|
P0 | 7 | 4 | 3 |
P1 | 1 | 2 | 2 |
P2 | 6 | 0 | 0 |
P3 | 0 | 1 | 1 |
P4 | 4 | 3 | 1 |
available table 剩餘資源表
銀行還剩下的金銀銅個數。
A | B | C |
---|---|---|
3 | 3 | 2 |
剩餘系統資源分配順序推演
- 拿着 available table (剩餘資源表),到 need table(還需放貸表) 比對。若 available table 的 A B C 滿足 need table 的某一行(也就是 available table 每一列都大於等於 need table 的某一行的每一列)。說明可以分配給這個進程,標記這一行。同時回收這一行對應的 allocation table 中已經分配的 A B C。更新 available table 的 A B C。以此類推,繼續比對 need table 中其他未標記的行。若最後 need table 所有行都有標記,說明存在一個給 P0、P1、P2、P3、P4 進程分配資源的順序。2. 拿着 available table 剩餘資源表,不滿足 need table 中任何一行。說明不存在一個給 P0、P1、P2、P3、P4 進程分配資源的順序。系統有可能進入死鎖。
銀行家算法圖解分析
存在的一個序列 P1 -> P3 -> P4 -> P0 -> P2
有沒有其他方法解決此問題
Banker’s Algorithm implemention
// Banker's Algorithm
#include <stdio.h>
int main()
{
// P0, P1, P2, P3, P4 are the Process names here
int n, m, i, j, k;
n = 5; // Number of processes
m = 3; // Number of resources
int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix
{ 2, 0, 0 }, // P1
{ 3, 0, 2 }, // P2
{ 2, 1, 1 }, // P3
{ 0, 0, 2 } }; // P4
int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix
{ 3, 2, 2 }, // P1
{ 9, 0, 2 }, // P2
{ 2, 2, 2 }, // P3
{ 4, 3, 3 } }; // P4
int avail[3] = { 3, 3, 2 }; // Available Resources
int finished[n], ans[n], index = 0;
for (k = 0; k < n; k++) {
finished[k] = 0;
}
int need[n][m];
for (i = 0; i < n; i++) {
for (j = 0; j < m; j++)
// 計算 need matrix
need[i][j] = max[i][j] - alloc[i][j];
}
int y = 0;
for (k = 0; k < 5; k++) {
for (i = 0; i < n; i++) {
if (finished[i] == 0) {
int flag = 0;
for (j = 0; j < m; j++) {
if (need[i][j] > avail[j]){
flag = 1;
break;
}
}
if (flag == 0) {
ans[index++] = i;
for (y = 0; y < m; y++)
avail[y] += alloc[i][y];
finished[i] = 1;
}
}
}
}
printf("Following is the SAFE Sequence\n");
for (i = 0; i < n - 1; i++)
printf(" P%d ->", ans[i]);
printf(" P%d", ans[n - 1]);
return (0);
}