python解决哲学家就餐问题(and型信号量)

最近操作系统刚学完这部分内容,老师要求下去自己实践一下,在网上看了看发现用python解决该问题的博文很少,而且好多都是错的,于是就自己写了一段代码

# and型信号量解决哲学家就餐问题
import time
import threading


class Philosophy(threading.Thread):
    def __init__(self, key, lefthand, righthand, hungry):
        threading.Thread.__init__(self)
        self.key = key  # 哲学家编号
        self.lefthand = lefthand  # True表示哲学家左手拿起筷子,False表示哲学家左手没有拿起筷子
        self.righthand = righthand
        self.hungry = hungry  # True表示哲学家饿了

    def pick(self):
        threadLock.acquire()
        if chopsticks[self.key] and chopsticks[(self.key + 1) % 5] and not self.lefthand and not self.righthand and self.hungry:  # 可以拿筷子
            time.sleep(5)
            chopsticks[(self.key + 1) % 5] = False
            self.lefthand = True
            print('哲学家%s拿起了左边的筷子!' % self.key)
            time.sleep(5)
            chopsticks[self.key] = False  # 哲学家的筷子被拿
            self.righthand = True  # 哲学家右手拿起筷子
            print('哲学家%s拿起了右边的筷子!' % self.key)
        threadLock.release()

    def eat(self):
        if self.lefthand and self.righthand and self.hungry:  # 可以开始吃饭
            time.sleep(5)
            print('哲学家%s开始吃饭' % self.key)
            time.sleep(5)
            print('哲学家%s吃完饭了' % self.key)
            self.hungry = False
            time.sleep(5)
            print('哲学家%s放下筷子开始思考' % self.key)
            self.lefthand = False  # 哲学家左手放下筷子
            self.righthand = False  # 哲学家右手放下筷子
            chopsticks[self.key] = True  # 哲学家的筷子可以用
            chopsticks[(self.key + 1) % 5] = True  # 哲学家右边的筷子可以用

    def run(self):
        while True:
            self.pick()
            self.eat()


threadLock = threading.Lock()
chopsticks = [True, True, True, True, True]
philosophy0 = Philosophy(0, False, False, True)
philosophy1 = Philosophy(1, False, False, True)
philosophy2 = Philosophy(2, False, False, True)
philosophy3 = Philosophy(3, False, False, True)
philosophy4 = Philosophy(4, False, False, True)

philosophy0.start()
philosophy1.start()
philosophy2.start()
philosophy3.start()
philosophy4.start()

结果如下:
哲学家0拿起了左边的筷子!
哲学家0拿起了右边的筷子!
哲学家0开始吃饭
哲学家2拿起了左边的筷子!
哲学家2拿起了右边的筷子!
哲学家0吃完饭了
哲学家2开始吃饭
哲学家0放下筷子开始思考
哲学家4拿起了左边的筷子!
哲学家2吃完饭了
哲学家2放下筷子开始思考
哲学家4拿起了右边的筷子!
哲学家4开始吃饭
哲学家1拿起了左边的筷子!
哲学家4吃完饭了
哲学家1拿起了右边的筷子!
哲学家4放下筷子开始思考
哲学家1开始吃饭
哲学家3拿起了左边的筷子!
哲学家1吃完饭了
哲学家3拿起了右边的筷子!
哲学家1放下筷子开始思考
哲学家3开始吃饭
哲学家3吃完饭了
哲学家3放下筷子开始思考

  • 12
    点赞
  • 50
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值