给定:一个系统具有R个相同的资源,P个进程在争夺它们,而N是每个进程的最大需求。任务是找到所需的最少资源数量,以使死锁永远不会发生。
公式:
R >= P * (N - 1) + 1
例子:
Input : P = 3, N = 4
Output : R >= 10
Input : P = 7, N = 2
Output : R >= 8
方法:
Consider, 3 process A, B and C.
Let, Need of each process is 4
Therefore, The maximum resources require will be 3 * 4 = 12 i.e, Give 4 resources to each Process.
And, The minimum resources required will be 3 * (4 – 1) + 1 = 10.
i.e, Give 3 Resources to each of the Process, and we are left out with 1 Resource.
That 1 resource will be given to any of the Process A, B or C.
So that after using that resource by any one of the Process, It left the resources and that resources will be used by any other Process and thus Deadlock will Never Occur.
C++
// C++ implementation of above program.
#include
using namespace std;
// function that calculates
// the minimum no. of resources
int Resources(int process, int need)
{
int minResources = 0;
// Condition so that deadlock
// will not occuur
minResources = process * (need - 1) + 1;
return minResources;
}
// Driver code
int main()
{
int process = 3, need = 4;
cout << "R >= " << Resources(process, need);
return 0;
}
Java
// Java implementation of above program
class GFG
{
// function that calculates
// the minimum no. of resources
static int Resources(int process, int need)
{
int minResources = 0;
// Condition so that deadlock
// will not occuur
minResources = process * (need - 1) + 1;
return minResources;
}
// Driver Code
public static void main(String args[])
{
int process = 3, need = 4;
System.out.print("R >= ");
System.out.print(Resources(process, need));
}
}
Python3
# Python 3 implementation of
# above program
# function that calculates
# the minimum no. of resources
def Resources(process, need):
minResources = 0
# Condition so that deadlock
# will not occuur
minResources = process * (need - 1) + 1
return minResources
# Driver Code
if __name__ == "__main__" :
process, need = 3, 4
print("R >=", Resources(process, need))
# This Code is Contributed
# by Naman_Garg
C#
// C# implementation of above program
using System;
class GFG
{
// function that calculates
// the minimum no. of resources
static int Resources(int process, int need)
{
int minResources = 0;
// Condition so that deadlock
// will not occuur
minResources = process * (need - 1) + 1;
return minResources;
}
// Driver Code
public static void Main()
{
int process = 3, need = 4;
Console.Write("R >= ");
Console.Write(Resources(process, need));
}
}
// This code is contributed
// by Sanjit_Prasad
输出:
R >= 10