40个进程随机申请资源,满足则分配资源。
import numpy as np
import time
import random as rd
class PCB:
safe_seq=[]#安全序列
X=0
def __init__(self, ID,ID_request, still_request,ab_resource):
self.ID_request=ID_request#该进程所需总资源
self.ID=ID#进程ID
self.still_request=still_request#任需资源
self.ab_resource=ab_resource#可用资源
self.X=len(self.ID)
def applican(self):#随机进程申请资源,并判断是否满足,不满足,则返回-1,满足则返回进程号,用于下一步分配
app_ID=rd.sample(self.ID,1)#挑选随机进程
print(app_ID[0],"号进程正在申请资源")
z=self.ab_resource-self.still_request[app_ID[0]]
#print(z)
min_r=min(z)
if min_r<0:
print("当前资源分配后会进入不安全状态,申请失败")
return -1
else:
print("满足资源分配要求,即将分配")
return app_ID[0]
def fenpei(self,ID):#分配资源
self.ab_resource=np.array(self.ab_resource)+np.array(self.ID_request[ID]) #分配完成,资源释放
self.safe_seq.append(ID)
self.ID.remove(ID)
print("分配成功,返还资源,当前可用资源数为:",self.ab_resource)
def diaoyong(self):#判断是否分配资源
z=PCB.applican(self)
if z>=0:
PCB.fenpei(self,z)
def shuchu(self):
print("所以进程已完成\n")
print("安全序列为",self.safe_seq)
def diaoyong1(self):
while(True):#一直申请资源,直到全部完成
#for i in range(10):
PCB.diaoyong(self)
time.sleep(0.5)
if len(self.safe_seq)==self.X:#此时已经全部完成
PCB.shuchu(self)
break
ID=[]#进程ID
ID_request=[]#进程所需要的总资源
ID_divider=[]#已分配资源
avle_source=[2,3,2,2]#每种资源的剩余
#ID_still_request=所需资源-已分配资源=任需资源
#设置40个进程
for i in range(40):
#print(i)
ID.append(i)
for i in range(4):
ID_ziyuan=[]
fenpei=[]
a=rd.randint(2,6)
a1=rd.randint(0,2)
b=rd.randint(3,4)
b1=rd.randint(0,3)
c=rd.randint(3,4)
c1=rd.randint(0,3)
d=rd.randint(3,4)
d1=rd.randint(0,3)
ID_ziyuan.append(a)
ID_ziyuan.append(b)
ID_ziyuan.append(c)
ID_ziyuan.append(d)
fenpei.append(a1)
fenpei.append(b1)
fenpei.append(c1)
fenpei.append(d1)
ID_request.append(ID_ziyuan)
ID_divider.append(fenpei)
for i in range(40):
print(i,"号",ID_request[i])
ID_still_request=np.array(ID_request)-np.array(ID_divider)#任需资源数
P=PCB(ID,ID_request,ID_still_request,avle_source)
P.diaoyong1()