resourceNum = 3
processNum = 5
A = 10
B = 5
C = 7
MAXes = [
[7,5,3],
[3,2,2],
[9,0,2],
[2,2,2],
[4,3,3]
]
Allocationes = [
[0,1,0],
[2,0,0],
[3,0,2],
[2,1,1],
[0,0,2]
]
# A = 10
# B = 5
# C = 7
# MAXes = [
# [7,5,3],
# [3,2,2],
# [9,0,2],
# [4,2,2],
# [5,3,3]
# ]
# Allocationes = [
# [0,2,0],
# [2,0,2],
# [3,0,2],
# [2,1,1],
# [2,2,2]
# ]
class Process:
def __init__(self,MAX:list,Allocation:list,Name:str):
self.name = Name
self.MAX = MAX
self.Allocation = Allocation
self.Need = [0 for i in range(resourceNum)]
for i in range(resourceNum):
self.Need[i] = self.MAX[i] - self.Allocation[i]
self.COMPLETE = False
class Processes:
def __init__(self):
self.processes = []
self.left = 0
def add(self,process:Process):
self.processes.append(process)
self.left += 1
def complete(self,process:Process):
for i in self.processes:
if i == process:
i.COMPLETE = True
self.left -= 1
def main():
Available = [0 for i in range(resourceNum)]
P0 = Process(MAXes[0],Allocationes[0],"P0")
P1 = Process(MAXes[1],Allocationes[1],"P1")
P2 = Process(MAXes[2],Allocationes[2],"P2")
P3 = Process(MAXes[3],Allocationes[3],"P3")
P4 = Process(MAXes[4],Allocationes[4],"P4")
PS = Processes()
PS.add(P0)
PS.add(P1)
PS.add(P2)
PS.add(P3)
PS.add(P4)
for i in range(resourceNum):
sum_alloc = 0
for j in range(processNum):
sum_alloc += Allocationes[j][i]
Available[i] = [A,B,C][i] - sum_alloc
#print(Available)
safe_list = []
can_be_allocated_flag = True
exist_process_completion_flag = True
print("Detailed search content:\n")
print("2023045036 Allocation",(resourceNum-2)*'\t',"Work","\t\tSecurity sequence")
while PS.left != 0 and exist_process_completion_flag == True: # all process were complete, or last cycle didn't do anything
exist_process_completion_flag = False
for i in PS.processes:
Work = []
can_be_allocated_flag = True
if i.COMPLETE == True:
continue
for j in range(resourceNum):
if i.Need[j] > Available[j]:
can_be_allocated_flag = False
break
if can_be_allocated_flag == True: # if the resources can be allocated to this process
safe_list.append(i.name)
PS.complete(i)
exist_process_completion_flag = True
for j in range(resourceNum):
Available[j] += i.Allocation[j] # recycle this process' resource
for j in range(resourceNum): # compute Work resourse
Work.append(Available[j]-i.Allocation[j])
#print(safe_list)
print('2023045036',i.Allocation,'\t',Work,'\t',safe_list)
if exist_process_completion_flag == False:
print("\nCan not find a Security sequence!\n")
else:
print("\nSecurity sequence: ",safe_list)
if __name__ == "__main__":
main()
银行家算法
于 2025-11-03 00:14:26 首次发布
7468

被折叠的 条评论
为什么被折叠?



