class BankersAlgorithm:
def __init__(self, max_demand, allocation, available):
self.max_demand = max_demand
self.allocation = allocation
self.available = available
self.need = [[max_demand[i][j] - allocation[i][j] for j in range(len(available))] for i in range(len(max_demand))]
def is_safe(self):
work = self.available[:]
finish = [False] * len(self.allocation)
safe_sequence = []
while len(safe_sequence) < len(self.allocation):
for i in range(len(self.allocation)):
if not finish[i] and all(self.need[i][j] <= work[j] for j in range(len(work))):
for j in range(len(work)):
work[j] += self.allocation[i][j]
finish[i] = True
safe_sequence.append(i)
break
else:
break
if len(safe_sequence) == len(self.allocation):
print("系统安全,安全序列为:", ['P' + str(i) for i in safe_sequence])
return True
else:
print("系统不安全,没有安全序列")
return False
# 数据初始化
if __name__ == "__main__":
allocation = [
[0, 1, 0, 2], # P0
[1, 0, 0, 0], # P1
[1, 3, 5, 4], # P2
[0, 6, 3, 3], # P3
[0, 0, 1, 2], # P4
]
max_demand = [
[2, 1, 0, 2], # P0
[1, 7, 5, 0], # P1
[2, 3, 5, 6], # P2
[0, 6, 5, 2], # P3
[0, 6, 5, 6], # P4
]
# 系统当前可用资源
available = [1, 5, 2, 0]
bankers_algorithm = BankersAlgorithm(max_demand, allocation, available)
bankers_algorithm.is_safe()