Smipple is shutting down Nov 30, 2017. Some features are currently disabled.
Profile image for Thomas Simonsen simoth00
Blocking
Language
Python
Tags
Dining Philosophers

Dining Philosophers

1 import threading 2 from time import sleep 3 import os 4 5 # Layout of the table (P = philosopher, f = fork): 6 # P0 7 # f3 f0 8 # P3 P1 9 # f2 f1 10 # P2 11 12 # Number of philosophers at the table. There'll be the same number of forks. 13 numPhilosophers = 4 14 15 # Lists to hold the philosophers and the forks. 16 # Philosophers are threads while forks are locks. 17 philosophers = [] 18 forks = [] 19 20 class Philosopher(threading.Thread): 21 def __init__(self, index): 22 threading.Thread.__init__(self) 23 self.index = index 24 25 def run(self): 26 # Left fork has same index as self.index. 27 # Right fork has index smaller by 1, except for the first philosopher 28 leftForkIndex = self.index 29 rightForkIndex = (self.index - 1) if self.index != 0 else (numPhilosophers - 1) 30 31 forkPair = ForkPair(leftForkIndex, rightForkIndex) 32 33 # Eat forever 34 while True: 35 forkPair.pickUp() 36 print("Philosopher", self.index, "eats.") 37 forkPair.putDown() 38 39 class ForkPair: 40 def __init__(self, leftForkIndex, rightForkIndex): 41 # Order forks by index 42 if leftForkIndex < rightForkIndex: 43 self.firstFork = forks[leftForkIndex] 44 self.secondFork = forks[rightForkIndex] 45 else: 46 self.firstFork = forks[rightForkIndex] 47 self.secondFork = forks[leftForkIndex] 48 49 def pickUp(self): 50 # Pick the fork with lower index first 51 self.firstFork.acquire() 52 self.secondFork.acquire() 53 54 def putDown(self): 55 self.firstFork.release() 56 self.secondFork.release() 57 58 if __name__ == "__main__": 59 # Create our philosophers and forks 60 for i in range(0, numPhilosophers): 61 philosophers.append(Philosopher(i)) 62 forks.append(threading.Lock()) 63 64 # All philosophers start eating 65 for i in range(0, numPhilosophers): 66 philosophers[i].start() 67 68 # Allow CTRL + C to exit the program 69 try: 70 while True: sleep(0.1) 71 except (KeyboardInterrupt, SystemExit): 72 os._exit(0)

Comments