水瓶如(认证作者)
纳兰辞特邀用户:水瓶如,总共发布文章400篇。
Bankers是一种资源分配算法,它可以帮助解决多个进程同时请求不同数量的资源的问题。它允许系统在所有进程都能得到满足的情况下,尽可能地分配资源。
1. 原理:Bankers算法基于安全性原则,即当前状态必须保持安全,也就是说,如果某个进程正在使用资源,那么它将不会因为其他进程而失去资源。
2. 步骤:Bankers算法包括以下几个步骤:
(1) 确定系统中可用的资源数量。
(2) 为每个进程确定最大需求量。
(3) 进行安全性检查,确定是否存在一种方案,使得所有进程都能得到满足。
(4) 如果存在安全的方案,则分配资源;否则,等待直到有足够的资源可供分配。
3. 代码示例:
// Banker's Algorithm
#include
// Number of processes
int P = 5;
// Number of resources
int R = 3;
// Function to find the need of each process
void calculateNeed(int need[P][R], int maxm[P][R],
int allot[P][R])
{
// Calculating Need of each P
for (int i = 0 ; i< P ; i++)
for (int j = 0 ; j< R ; j++)
// Need of instance = maxm instance -
// allocated instance
need[i][j] = maxm[i][j] - allot[i][j];
}
// Function to find the system is in safe state or not
bool isSafe(int processes[], int avail[], int maxm[][R],
int allot[][R])
{
int need[P][R];
// Function to calculate need matrix
calculateNeed(need, maxm, allot);
// Mark all processes as infinish
bool finish[P] = {0};
// To store safe sequence
int safeSeq[P];
// Make a copy of available resources
int work[R];
for (int i = 0; i< R ; i++)
work[i] = avail[i];
// While all processes are not finished
// or system is not in safe state.
int count = 0;
while (count< P)
{
// Find a process which is not finish and
// whose needs can be satisfied with current
// work[] resources.
bool found = false;
for (int p = 0; p< P; p++)
{
// First check if a process is finished,
// if no, go for next condition
if (finish[p] == 0)
{
// Check if for all resources of
// current P need is less
// than work
int j;
for (j = 0; j< R; j++)
if (need[p][j] >work[j])
break;
// If all needs of p were satisfied.
if (j == R)
{
// Add the allocated resources of
// current P to the available/work
未经允许不得转载: 纳兰辞 » bankers是什么 bankers的翻译