Untitled

mail@pastecode.io avatar
unknown
plain_text
7 months ago
1.5 kB
0
Indexable
Never
mport 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):
    for _ in range(3):  # Eat 3 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