在复习操作系统的时候,顺手实现了一遍银行家算法。对于理论,本人理解了,也根据书本提供的文字描述用Python实现了一遍,虽然网上已经有很多相同的例子,但为了理解透彻,自己实现了一遍。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@Author ChenYuan
@Name 银行家算法.py
@Describe
@Version 1.0
"""
import numpy as np
class BankerAlgorithm():
def __init__(self, Available, Allocation, Max, Request):
assert len(Allocation) == len(Max) == len(Request), '输入进程数量不一致,请检查输入!'
assert len(Available) == len(Allocation[0]) == len(Max[0]) == len(Request[0]), '输入资源数量不一致,请检查输入!'
self.Available = np.array(Available)
self.Allocation = np.array(Allocation)
self.Max = np.array(Max)
self.Request = np.array(Request)
self.Need = Max - Allocation
print(self.Need)
@staticmethod
def _SacurityAlgorithm(Available, Need, Allocation):
Work = Available
allocation_sequence = []
index = list(range(len(Need))) # 设置一个列表,存放下标,用于循环和删除
while True:
temp_index = index.copy() # 复制值,避免地址复制
for i in temp_index:
if Work.tolist() >= Need[i].tolist():
Work += Allocation[i]
allocation_sequence.append(i)
index.remove(i)
if temp_index == index:
# 如果这一次的循环后,下标结果和上一个循环一样,则循环结束
break
allocation_result = ['True' if i in allocation_sequence else 'False' for i in range(len(Need)) ]
return allocation_result, allocation_sequence
def BankerAlgorithm(self, i):
if self.Request[i].tolist() <= self.Need[i].tolist():
if self.Request[i].tolist() <= self.Available.tolist():
self.Available -= self.Request[i]
self.Allocation[i] += self.Request[i]
self.Need[i] -= self.Request[i]
allocation_result, allocation_sequence = self._SacurityAlgorithm(self.Available, self.Need, self.Allocation)
if 'False' in allocation_result:
print('对进程{}的请求:{},是不安全的。'.format(i, self.Request[i]))
else:
print('对进程{}的请求:{},是安全的。'.format(i, self.Request[i]))
print('分配的顺序为:{}'.format(allocation_sequence))
print('分配结果如下(True为分配成功,False为失败):\n{}'.format(allocation_result))
else:
print('对进程{}的请求:{},大于当前可以分配的资源:。'.format(i, self.Request[i], self.Available))
else:
print('对进程{}的请求:{},大于它需求的资源:。'.format(i, self.Request[i], self.Need[i]))
if __name__ == '__main__':
Available = [2, 3, 0]
Max = [[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [4, 3, 3]]
Allocation = [[0, 1, 0], [3, 0, 2], [3, 0, 2], [2, 1, 1], [0, 0, 2]]
Request = [[1, 0, 2], [0, 2, 0], [1, 0, 2], [1, 0, 2], [1, 0, 2]]
Available, Allocation = np.array(Available), np.array(Allocation)
Max, Request = np.array(Max), np.array(Request)
ba = BankerAlgorithm(Available, Allocation, Max, Request)
ba.BankerAlgorithm(1)
有什么问题,或者哪里错了,请留言,谢谢。