import numpy
#创建Available
Available=[]
count=1
print("输入可利用资源的类别的个数,按回车键继续输入,-1结束:")
while True:
print("第"+str(count)+"类资源的个数")
m=int(input())
if m==-1:
break
count=count+1
Available.append(m)
print(Available)
Available=numpy.array(Available)
#创建Max
n=int(input("输入进程的个数"))
Max=[ [] for i in range(n)]
print("输入进程对资源的最大需求,按回车键继续输入")
for i in range(n):
for j in range(len(Available)):
k=int(input("第"+str(i+1)+"个进程对第"+str(j+1)+"类资源的最大需求"))
Max[i].append(k)
Max=numpy.array(Max)
print(numpy.array(Max))
#创建分配矩阵Allocation
Allocation=[ [] for i in range(n)]
print("输入系统中每一类资源当前已经分配给每一进程的资源数,按回车键继续输入")
for i in range(n):
for j in range(len(Available)):
k=int(input("第"+str(i+1)+"个进程对第"+str(j+1)+"类资源的分配的资源数"))
Allocation[i].append(k)
Allocation=numpy.array(Allocation)
print(numpy.array(Allocation))
#需求矩阵Need
#Need=numpy.zeros((n,len(Available)))
Need=numpy.array(Max)-numpy.array(Allocation)
print("此时所需要的资源数是")
print(Need)
#银行家算法
m=len(Available)
Request=numpy.zeros((n,m))
Request=numpy.array(Request)
print(Request)
i,j=map(int,input("输入你要申请资源的进程号和资源类别号(从0开始计数,空格分隔,输完了按回车谢谢,Python这个没法控制)").split(" "))
k=int(input("输入申请资源量:"))
Request[i][j]=k
if k+Allocation[i][j]<=Max[i][j]:
if k<=Available[j]:
Available[j]=Available[j]-Request[i][j]
Allocation[i][j]=Allocation[i][j]+Request[i][j]
Need[i][j]=Need[i][j]-Request[i][j]
else:
print("请求不满足,返回")
else:
print("超过最大需求量,错误")
work=Available
finish=numpy.zeros(m)
for i in range(m):
for j in range(n):
if finish[i]==0 and Need[i][j]<=work[j]:
work[j]=work[j]+Allocation[i][j]
finish[i]=1
if numpy.all(finish):
print("系统处于安全状态")
else:
print("系统处于不安全状态")
04-28
5314