c语言实现银行家算法

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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值