Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.5 kB
3
Indexable
Never
import threading
import time

class DiningPhilosophersMonitor:
    def __init__(self, num_philosophers):
        self.forks = [threading.Condition() for _ in range(num_philosophers)]

    def pick_up_forks(self, philosopher_id):
        left_fork = philosopher_id
        right_fork = (philosopher_id + 1) % len(self.forks)
        with self.forks[left_fork]:
            with self.forks[right_fork]:
                print(f"Philosopher {philosopher_id} picked up forks.\n")

    def release_forks(self, philosopher_id):
        left_fork = philosopher_id
        right_fork = (philosopher_id + 1) % len(self.forks)
        with self.forks[left_fork]:
            with self.forks[right_fork]:
                print(f"Philosopher {philosopher_id} released forks.\n")

def philosopher(philosopher_id, monitor):
    # Eat 1 times
    print(f"Philosopher {philosopher_id} is thinking.\n")
    time.sleep(1)
    monitor.pick_up_forks(philosopher_id)
    print(f"Philosopher {philosopher_id} is eating.\n")
    time.sleep(1)
    monitor.release_forks(philosopher_id)

if __name__ == "__main__":
    num_philosophers = 5
    dining_monitor = DiningPhilosophersMonitor(num_philosophers)
    philosopher_threads = [threading.Thread(target=philosopher, args=(i, dining_monitor)) for i in range(num_philosophers)]
    for thread in philosopher_threads:
        thread.start()
    for thread in philosopher_threads:
        thread.join()
Leave a Comment