哲学家就餐问题python_Python实现哲学家就餐问题实例代码
时间: 2023-10-08 16:06:32 浏览: 71
好的,下面是 Python 实现哲学家就餐问题的示例代码:
```python
import threading
class Fork():
def __init__(self, fork_id):
self.id = fork_id
self.lock = threading.Lock()
def pick_up(self):
return self.lock.acquire(blocking=False)
def put_down(self):
self.lock.release()
class Philosopher(threading.Thread):
def __init__(self, philosopher_id, left_fork, right_fork):
threading.Thread.__init__(self)
self.id = philosopher_id
self.left_fork = left_fork
self.right_fork = right_fork
def run(self):
while True:
if self.left_fork.pick_up():
if self.right_fork.pick_up():
print("Philosopher", self.id, "is eating")
self.right_fork.put_down()
self.left_fork.put_down()
if __name__ == '__main__':
n_philosophers = 5 # 哲学家数量
forks = [Fork(i) for i in range(n_philosophers)]
philosophers = [Philosopher(i, forks[i], forks[(i+1)%n_philosophers]) for i in range(n_philosophers)]
for philosopher in philosophers:
philosopher.start()
```
这段代码通过创建 `Fork` 和 `Philosopher` 两个类来实现哲学家就餐问题。`Fork` 类代表叉子,有 `pick_up` 和 `put_down` 两个方法来拿起和放下叉子。`Philosopher` 类代表哲学家,有 `run` 方法,代表哲学家的行为。当哲学家拿起左边的叉子时,如果右边的叉子也能拿起来,则开始进餐,然后放下右边的叉子,再放下左边的叉子。代码中通过 `threading.Lock` 来实现互斥,防止哲学家之间同时拿起同一个叉子。