银行家算法原本是为银行系统设计的,以确保银行在发放现金贷款时,不会发生不能满足所有客户需要的情况,在OS中也可以用它来实现避免死锁。
为实现银行家算法,每一个新进程在进入系统时,它必须声明在运行过程中,可能需要每种类型资源的最大单元数目,其数目不应超过系统所拥有的资源总量。当进程请求一组资源时,系统必须要首先确定是否有足够的资源分配给该进程。若有,再进一步计算在将这些资源分配给进程后,是否会使系统处于不安全状态。如果不会,才将资源分配给它,否则让进程等待。
实现效果:
银行家算法中的数据结构
static int[][] max;
static int[][] allocation;
static int[][] need;
static int[] available;
其中
need[i][j] = max[i][j] - allocation[i][j];
银行家算法,当进程发起requeset时,按照以下步骤进行检查:
1.判断request是否小于need
// 判断need
boolean requestOK = false;
for (int j = 0; j < typeOfResource; j++) {
if (request[j] <= need[requestCustomerID][j]) {
requestOK = true;
} else {
requestOK = false;
break;
}
}
if (requestOK == false) {
print("\nNot Security! :-(");
return;
2.若1满足,则判断requset是否小于available
} else {
// 判断available
for (int j = 0; j < typeOfResource; j++) {
if (request[j] <= available[j]) {
requestOK = true;
} else {
requestOK = false;
break;
}
}
if (requestOK == false) {
print("\nNot Security! :-(");
return;
} else {
3.若2满足,则试探性分配资源
} else {
// 试探性分配资源
for (int j = 0; j < typeOfResource; j++) {
available[j] = available[j] - request[j];
allocation[requestCustomerID][j] = allocation[requestCustomerID][j]
+ request[j];
need[requestCustomerID][j] = need[requestCustomerID][j]
- request[j];
}
4.执行系统安全性算法
1)设置两个向量:工作向量Work=Available和Finish用以记录各个进程是否得到资源分配并运行完成, 默认Finish[i]=false。
work = available;
finish = new boolean[numberOfCustomer];
for (int i = 0; i < numberOfCustomer; i++) {
finish[i] = false;
}
2)从进程集合中找到Finish[i]=false;且Need[i,j]<=Work[j];
若找到则继续执行3),若找不到则判断是否所有Finish[]均为True,若是,则系统安全,若不是,则系统不安全,将所有试探性分配还原。
3)进程获得资源,顺利执行后释放它占据的资源
for (int x = 0; x < numberOfCustomer; x++) {
for (int i = 0; i < numberOfCustomer; i++) {
if (finish[i] == false) {
for (int j = 0; j < typeOfResource; j++) {
if (need[i][j] <= work[j]) {
finish[i] = true;
} else {
finish[i] = false;
break;
}
}
if (finish[i] == true) {
// 输出这个完成的进程
print("\n");
print("P" + i + ": Work: ");
for (int j = 0; j < typeOfResource; j++) {
System.out.print(work[j] + " ");
}
print("Need: ");
for (int j = 0; j < typeOfResource; j++) {
System.out.print(need[i][j] + " ");
}
print("Allocation: ");
for (int j = 0; j < typeOfResource; j++) {
System.out.print(allocation[i][j] + " ");
}
print("Work+Allocation: ");
for (int j = 0; j < typeOfResource; j++) {
System.out.print(work[j] + allocation[i][j] + " ");
}
for (int j = 0; j < typeOfResource; j++) {
work[j] = work[j] + allocation[i][j];
}
}
}
}
}
notFinish = false;
for (int i = 0; i < numberOfCustomer; i++) {
if (finish[i] == false) {
notFinish = true;
print("\nNot Security! :-(");
break;
}
}
if (notFinish == false) {
print("\nAvailable:");
for (int j = 0; j < typeOfResource; j++) {
available[j]=available_b[j]-request[j];
System.out.print(available[j] + " ");
}
print("\nSecurity! :-)");
}