哲学家就餐问题带界面python
时间: 2023-08-03 14:35:08 浏览: 156
好的,我可以为您提供一个简单的哲学家就餐问题的界面程序,使用Python语言编写。这个程序可以让您看到每个哲学家的状态和正在使用的筷子。
代码如下(注:需要安装Python tkinter模块):
```python
import threading
import time
import tkinter as tk
class Philosopher(threading.Thread):
def __init__(self, name, left_fork, right_fork, status_label):
super().__init__()
self.name = name
self.left_fork = left_fork
self.right_fork = right_fork
self.status_label = status_label
self.running = True
def run(self):
while self.running:
# Think
self.set_status("Thinking")
time.sleep(1)
# Pick up left fork
self.set_status("Picking up left fork")
self.left_fork.acquire()
# Pick up right fork
self.set_status("Picking up right fork")
self.right_fork.acquire()
# Eat
self.set_status("Eating")
time.sleep(1)
# Release right fork
self.set_status("Releasing right fork")
self.right_fork.release()
# Release left fork
self.set_status("Releasing left fork")
self.left_fork.release()
def set_status(self, status):
self.status_label.config(text=f"{self.name}: {status}")
class App:
def __init__(self):
self.window = tk.Tk()
self.window.title("Philosophers")
self.window.geometry("400x250")
self.status_labels = []
self.left_forks = []
self.right_forks = []
# Create forks
for i in range(5):
self.left_forks.append(threading.Lock())
self.right_forks.append(threading.Lock())
# Create philosopher threads
for i in range(5):
status_label = tk.Label(self.window, text=f"Philosopher {i+1}: Thinking")
status_label.pack()
self.status_labels.append(status_label)
philosopher = Philosopher(f"Philosopher {i+1}", self.left_forks[i], self.right_forks[(i+1)%5], status_label)
philosopher.start()
self.window.mainloop()
# Stop philosopher threads
for philosopher in self.philosophers:
philosopher.running = False
App()
```
运行这个程序后,您可以看到每个哲学家的状态和正在使用的筷子。当哲学家想要进餐时,它会先思考一会儿,然后尝试获取左右两边的筷子。如果它不能同时获取到这两个筷子,那么它就会等待一段时间后再次尝试获取筷子。当它成功获取到两个筷子后,它就会进餐一段时间,然后释放筷子,再次开始思考。
阅读全文