📜  银行家算法程序|设置 1(安全算法)

📅  最后修改于: 2022-05-13 01:56:11.253000             🧑  作者: Mango

银行家算法程序|设置 1(安全算法)

先决条件:银行家算法

银行家算法是一种资源分配和死锁避免算法,它通过模拟所有资源的预定最大可能数量的分配来测试安全性,然后进行“s 状态”检查以测试可能的活动,然后再决定是否应该允许分配接着说。

以下数据结构用于实现银行家算法:

'n'是系统中的进程数, 'm'是资源类型的数量。

可用的 :



  • 它是一个大小为“m”的一维数组,表示每种类型的可用资源的数量。
  • 可用[ j ] = k 表示有'k'个资源类型R j实例

最大限度 :

  • 它是一个大小为“ n*m”的二维数组,用于定义系统中每个进程的最大需求。
  • Max[ i, j ] = k 表示进程P i最多可以请求资源类型R j 的“k”个实例

分配:

  • 它是一个大小为“n*m”的二维数组,它定义了当前分配给每个进程的每种类型的资源数量。
  • Allocation[ i, j ] = k 表示进程P i当前分配了'k'个资源类型为R j实例

需要 :

  • 它是一个大小为“n*m”的二维数组,表示每个进程的剩余资源需求。
  • Need [ i, j ] = k 表示进程P i当前分配了“k”个资源类型为R j实例
  • 需要 [ i, j ] = Max [ i, j ] – 分配 [ i, j ]

分配i指定当前分配给进程 P i的资源,需要i指定进程 P i可能仍请求完成其任务的额外资源。

银行家算法由安全算法和资源请求算法组成

安全算法

判断系统是否处于安全状态的算法可以描述如下:

  1. 让 Work 和 Finish 分别是长度为 'm' 和 'n' 的向量。
    初始化:工作=可用
    完成 [i]=false;对于 i=1,2,……,n

  2. 找到一个 i 使得两者
    a) 完成 [i]=false
    b) Need_i<=work如果没有这样的我存在转到步骤(4)
  3. 工作=工作+分配_i
    完成[i]=真
    转到步骤(2)
  4. 如果对于所有 i,Finish[i]=true,
    然后系统处于安全状态。

安全顺序是进程可以安全执行的顺序。

在这篇文章中,完成了银行家算法的安全算法的实现。

C++
// C++ program to illustrate Banker's Algorithm
#include
using namespace std;
  
// Number of processes
const int P = 5;
  
// Number of resources
const 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
                    // resources i.e.free the resources
                    for (int k = 0 ; k < R ; k++)
                        work[k] += allot[p][k];
  
                    // Add this process to safe sequence.
                    safeSeq[count++] = p;
  
                    // Mark this p as finished
                    finish[p] = 1;
  
                    found = true;
                }
            }
        }
  
        // If we could not find a next process in safe
        // sequence.
        if (found == false)
        {
            cout << "System is not in safe state";
            return false;
        }
    }
  
    // If system is in safe state then
    // safe sequence will be as below
    cout << "System is in safe state.\nSafe"
         " sequence is: ";
    for (int i = 0; i < P ; i++)
        cout << safeSeq[i] << " ";
  
    return true;
}
  
// Driver code
int main()
{
    int processes[] = {0, 1, 2, 3, 4};
  
    // Available instances of resources
    int avail[] = {3, 3, 2};
  
    // Maximum R that can be allocated
    // to processes
    int maxm[][R] = {{7, 5, 3},
                     {3, 2, 2},
                     {9, 0, 2},
                     {2, 2, 2},
                     {4, 3, 3}};
  
    // Resources allocated to processes
    int allot[][R] = {{0, 1, 0},
                      {2, 0, 0},
                      {3, 0, 2},
                      {2, 1, 1},
                      {0, 0, 2}};
  
    // Check system is in safe state or not
    isSafe(processes, avail, maxm, allot);
  
    return 0;
}


Java
// Java program to illustrate Banker's Algorithm
import java.util.*;
  
class GFG
{
  
// Number of processes
static int P = 5;
  
// Number of resources
static int R = 3;
  
// Function to find the need of each process
static void calculateNeed(int need[][], int maxm[][],
                int allot[][])
{
    // 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
static boolean isSafe(int processes[], int avail[], int maxm[][],
            int allot[][])
{
    int [][]need = new int[P][R];
  
    // Function to calculate need matrix
    calculateNeed(need, maxm, allot);
  
    // Mark all processes as infinish
    boolean []finish = new boolean[P];
  
    // To store safe sequence
    int []safeSeq = new int[P];
  
    // Make a copy of available resources
    int []work = new int[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.
        boolean 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] == false)
            {
                // 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
                    // resources i.e.free the resources
                    for (int k = 0 ; k < R ; k++)
                        work[k] += allot[p][k];
  
                    // Add this process to safe sequence.
                    safeSeq[count++] = p;
  
                    // Mark this p as finished
                    finish[p] = true;
  
                    found = true;
                }
            }
        }
  
        // If we could not find a next process in safe
        // sequence.
        if (found == false)
        {
            System.out.print("System is not in safe state");
            return false;
        }
    }
  
    // If system is in safe state then
    // safe sequence will be as below
    System.out.print("System is in safe state.\nSafe"
        +" sequence is: ");
    for (int i = 0; i < P ; i++)
        System.out.print(safeSeq[i] + " ");
  
    return true;
}
  
// Driver code
public static void main(String[] args) 
{
    int processes[] = {0, 1, 2, 3, 4};
  
    // Available instances of resources
    int avail[] = {3, 3, 2};
  
    // Maximum R that can be allocated
    // to processes
    int maxm[][] = {{7, 5, 3},
                    {3, 2, 2},
                    {9, 0, 2},
                    {2, 2, 2},
                    {4, 3, 3}};
  
    // Resources allocated to processes
    int allot[][] = {{0, 1, 0},
                    {2, 0, 0},
                    {3, 0, 2},
                    {2, 1, 1},
                    {0, 0, 2}};
  
    // Check system is in safe state or not
    isSafe(processes, avail, maxm, allot);
}
}
  
// This code has been contributed by 29AjayKumar


Python3
# Python3 program to illustrate 
# Banker's Algorithm
  
# Number of processes 
P = 5
  
# Number of resources 
R = 3
  
# Function to find the need of each process 
def calculateNeed(need, maxm, allot):
  
    # Calculating Need of each P 
    for i in range(P):
        for j in range(R):
              
            # 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
def isSafe(processes, avail, maxm, allot):
    need = []
    for i in range(P):
        l = []
        for j in range(R):
            l.append(0)
        need.append(l)
          
    # Function to calculate need matrix 
    calculateNeed(need, maxm, allot)
  
    # Mark all processes as infinish 
    finish = [0] * P
      
    # To store safe sequence 
    safeSeq = [0] * P 
  
    # Make a copy of available resources 
    work = [0] * R 
    for i in range(R):
        work[i] = avail[i] 
  
    # While all processes are not finished 
    # or system is not in safe state. 
    count = 0
    while (count < P):
          
        # Find a process which is not finish 
        # and whose needs can be satisfied 
        # with current work[] resources. 
        found = False
        for p in range(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
                for j in range(R):
                    if (need[p][j] > work[j]):
                        break
                      
                # If all needs of p were satisfied. 
                if (j == R - 1): 
                  
                    # Add the allocated resources of 
                    # current P to the available/work 
                    # resources i.e.free the resources 
                    for k in range(R): 
                        work[k] += allot[p][k] 
  
                    # Add this process to safe sequence. 
                    safeSeq[count] = p
                    count += 1
  
                    # Mark this p as finished 
                    finish[p] = 1
  
                    found = True
                  
        # If we could not find a next process 
        # in safe sequence. 
        if (found == False):
            print("System is not in safe state")
            return False
          
    # If system is in safe state then 
    # safe sequence will be as below 
    print("System is in safe state.",
              "\nSafe sequence is: ", end = " ")
    print(*safeSeq) 
  
    return True
  
# Driver code 
if __name__ =="__main__":
      
    processes = [0, 1, 2, 3, 4]
  
    # Available instances of resources 
    avail = [3, 3, 2] 
  
    # Maximum R that can be allocated 
    # to processes 
    maxm = [[7, 5, 3], [3, 2, 2],
            [9, 0, 2], [2, 2, 2],
            [4, 3, 3]]
  
    # Resources allocated to processes 
    allot = [[0, 1, 0], [2, 0, 0],
             [3, 0, 2], [2, 1, 1],
             [0, 0, 2]] 
  
    # Check system is in safe state or not 
    isSafe(processes, avail, maxm, allot) 
  
# This code is contributed by
# Shubham Singh(SHUBHAMSINGH10)


C#
// C# program to illustrate Banker's Algorithm
using System;
  
class GFG
{
      
// Number of processes
static int P = 5;
  
// Number of resources
static int R = 3;
  
// Function to find the need of each process
static void calculateNeed(int [,]need, int [,]maxm,
                int [,]allot)
{
    // 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
static bool isSafe(int []processes, int []avail, int [,]maxm,
            int [,]allot)
{
    int [,]need = new int[P,R];
  
    // Function to calculate need matrix
    calculateNeed(need, maxm, allot);
  
    // Mark all processes as infinish
    bool []finish = new bool[P];
  
    // To store safe sequence
    int []safeSeq = new int[P];
  
    // Make a copy of available resources
    int []work = new int[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] == false)
            {
                // 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
                    // resources i.e.free the resources
                    for (int k = 0 ; k < R ; k++)
                        work[k] += allot[p,k];
  
                    // Add this process to safe sequence.
                    safeSeq[count++] = p;
  
                    // Mark this p as finished
                    finish[p] = true;
  
                    found = true;
                }
            }
        }
  
        // If we could not find a next process in safe
        // sequence.
        if (found == false)
        {
            Console.Write("System is not in safe state");
            return false;
        }
    }
  
    // If system is in safe state then
    // safe sequence will be as below
        Console.Write("System is in safe state.\nSafe"
        +" sequence is: ");
    for (int i = 0; i < P ; i++)
            Console.Write(safeSeq[i] + " ");
  
    return true;
}
  
// Driver code
static public void Main ()
{
    int []processes = {0, 1, 2, 3, 4};
  
    // Available instances of resources
    int []avail = {3, 3, 2};
  
    // Maximum R that can be allocated
    // to processes
    int [,]maxm = {{7, 5, 3},
                    {3, 2, 2},
                    {9, 0, 2},
                    {2, 2, 2},
                    {4, 3, 3}};
  
    // Resources allocated to processes
    int [,]allot = {{0, 1, 0},
                    {2, 0, 0},
                    {3, 0, 2},
                    {2, 1, 1},
                    {0, 0, 2}};
  
    // Check system is in safe state or not
    isSafe(processes, avail, maxm, allot);
  
    }
}
  
// This code has been contributed by ajit.


输出:

System is in safe state.
Safe sequence is: 1 3 4 0 2

插图 :
考虑具有五个进程 P0 到 P4 和三种资源类型 A、B、C 的系统。资源类型 A 有 10 个实例,B 有 5 个实例,C 类有 7 个实例。假设在系统快照之后的时间 t0 已拍摄:

我们必须确定新的系统状态是否安全。为此,我们需要在上面给定的分配图表上执行安全算法。
银行家算法

以下是资源分配图:
银行家
执行安全算法表明序列满足安全要求。

时间复杂度= O(n*n*m),其中 n = 进程数,m = 资源数。