银行家算法的Python实现

'''银行家算法
    Dijkstra在1965年提出的银行家算法是著名的死锁避免算法
    博客地址:https://www.cnblogs.com/wkfvawl/p/11929508.html
'''
import pandas as pd


class Bank:

    def __init__(self, **resources: int):
        '''
        @param: resources
            资源的数量
        '''
        self.resources = pd.DataFrame(resources, index=["total"])
        self.allocation = pd.DataFrame(
            [], index=self.resources.keys(), dtype=int)
        self.maxs = pd.DataFrame([], index=self.resources.keys(), dtype=int)

    def _avaliable(self, allocation):
        aval = self.resources - allocation.sum(axis=1)
        aval.index = ["avaliable"]
        return aval

    def _safe_check(self, allocation):
        if allocation.empty:
            return True

        aval = self._avaliable(allocation)
        need = self._need(allocation)

        for custom in allocation.columns:
            t = need[custom] <= aval
            if (t.all(axis=None)):
                temp = allocation.copy().drop(columns=[custom])
                if self._safe_check(temp):
                    return True

        return False

    def is_safe(self):
        '''是否安全
        '''
        return self._safe_check(self.allocation)

    def lend(self, custom, **need_resources: int):
        allocation = self.allocation.copy()

        for resource, number in need_resources.items():
            allocation[custom][resource] += number

        if self._safe_check(allocation):
            self.allocation = allocation
            print(custom, need_resources, "已分配")
        else:
            print(custom, need_resources, "不安全,拒绝分配")

    def _need(self, allocation):
        return self.maxs - allocation

    def add_custom(self, name, **max_resources: int):
        '''
        @param: name
            客户名称
        @param: max_resources
            申请资源的最大额度
        '''
        self.maxs = pd.concat([self.maxs, pd.DataFrame(
            {name: max_resources})], axis=1).fillna(0).astype(int)
        self.allocation[name] = 0

    def table(self):
        '''列出资源和进程表格信息'''
        print(pd.concat([self.maxs.T, self.allocation.T, self._need(self.allocation).T], axis=1, keys=[
              "max", "allocation", "need"]))
        print(pd.concat([self._avaliable(self.allocation), self.resources]))



def main():
    bank = Bank(R1=9, R2=3, R3=6)

    bank.add_custom("p1",  R1=3, R2=2, R3=2)
    bank.add_custom("p2",  R1=6, R2=1, R3=3)
    bank.add_custom("p3",  R1=3, R2=1, R3=4)
    bank.add_custom("p4",  R1=4, R2=2, R3=2)

    bank.lend("p1", R1=1)
    bank.lend("p2", R1=5, R2=1, R3=1)
    bank.lend("p3", R1=2, R2=1, R3=1)
    bank.lend("p4", R1=0, R2=0, R3=2)


    # 1. 此刻是否安全
    print(bank.is_safe())

    # 2. p2发出请求(1,0,1),是否安全
    bank.lend("p2", R1=1, R2=0, R3=1)

    # 3. p1发出请求(1,0,1),是否安全
    bank.lend("p1", R1=1, R2=0, R3=1)

    # 4. p3发出请求(0,0,1),是否安全
    bank.lend("p3", R1=0, R2=0, R3=1)



if __name__ == "__main__":
    main()


  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
银行家算法是避免死锁的一种重要方法,本程序用java编程语言对其进行了实现。 当用户申请一组资源时,系统必须做出判断,如果把这些资源分出去,系统是否还处于安全状态。 若是,就可以分出这些资源;否则,该申请暂不予满足。 1.数据结构 假设有M个进程N类资源,则有如下数据结构: MAX[M*N] M个进程对N类资源的最大需求量 AVAILABLE[N] 系统可用资源数 ALLOCATION[M*N] M个进程已经得到N类资源的资源量 NEED[M*N] M个进程还需要N类资源的资源量 2.银行家算法 设进程I提出请求Request[N],则银行家算法按如下规则进行判断。 (1)如果Request[N]<=NEED[I,N],则转(2);否则,出错。 (2)如果Request[N]<=AVAILABLE,则转(3);否则,出错。 (3)系统试探分配资源,修改相关数据: AVAILABLE=AVAILABLE-REQUEST ALLOCATION=ALLOCATION+REQUEST NEED=NEED-REQUEST (4)系统执行安全性检查,如安全,则分配成立;否则试探险性分配作废,系统恢复原状,进程等待。 3.安全性检查 (1)设置两个工作向量WORK=AVAILABLE;FINISH[M]=FALSE (2)从进程集合中找到一个满足下述条件的进程, FINISH[i]=FALSE NEED<=WORK 如找到,执行(3);否则,执行(4) (3)设进程获得资源,可顺利执行,直至完成,从而释放资源。 WORK=WORK+ALLOCATION FINISH=TRUE GO TO 2 (4)如所有的进程Finish[M]=true,则表示安全;否则系统不安全。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值