代码简单易懂,附注释,供参考
/**
* 银行家算法
**/
#include <bitset>
#include <algorithm>
#include <span>
constexpr unsigned int N { 10 }; /* process number */
constexpr unsigned int M { 5 }; /* resouce number */
unsigned int Available[M] {};/* 开始时系统预留的资源数量 */
unsigned int Allocation[N][M] {};/* 进程执行前的预分配资源 */
unsigned int Need[N][M] {};/* 进程执行需要额外分配的资源 */
unsigned int Max[N][M] {};/* 执行进程最大需要的资源 */
unsigned int requestID {};/* 进程提出资源请求 */
unsigned int requestRSC[M] {};
unsigned int Work[M] {};/* 跟踪当前资源剩余数量 */
std::bitset<N> Finish {};
bool enough(unsigned int process) noexcept {/* 检查当前系统剩余资源是否足够支撑该线程运行 */
for(unsigned int j {}; j < M; j ++)
if(Need[process][j] > Work[j])
return false;
return true;
}
void release(unsigned int process) noexcept { /* 一个进程执行完后会释放对应资源 */
for(unsigned int j {}; j < M; j ++)
Work[j] += Allocation[process][j];
}
int main() {
for(unsigned int j {}; j < M; j ++)
if(requestRSC[j] > Need[requestID][j] /* 原本就不需要这么多 */|| requestRSC[j] > Available[j] /* 系统资源根本不够用 */) {
std::puts("request not permitted");
return 0;
}
for(unsigned int j {}; j < M; j ++) {
Allocation[requestID][j] += requestRSC[j]; /* 申请成功,于是预分配资源多了 */
Need[requestID][j] -= requestRSC[j]; /* 那么执行这个进程,还需要的额外资源就少了 */
Available[j] -= requestRSC[j]; /* 那一开始的预留资源就少了 */
}
for(unsigned int i {}; i < N; i ++)
for(unsigned int j {}; j < M; j ++)
Max[i][j] += Need[i][j] + Allocation[i][j]; /* Max的含义就一目了然了*/
std::copy_n(std::cbegin(Available), std::min(std::size(Available), std::size(Work)), std::begin(Work));
/* Work工作向量 实时跟踪当前执行过程中,剩余的资源个数 */
while(true)
for(unsigned int i {}; i < N; i ++) {
if(!Finish[i] && enough(i)) {
/* 模拟执行该进程 */
release(i); /* 执行完释放资源 */
Finish[i] = true; /* 选到了就剔除掉 */
break; // 再次从头开始选下一个进程
} else goto jump_out;
}
jump_out:
for(unsigned int i {}; i < N; i ++)
if(! Finish[i]) {
std::puts("dead lock");
return 0;
}
std::puts("safe");
return 0;
}