fndemers

Untitled

Jan 20th, 2021
758
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/python3  
  2. # -*- coding: utf-8 -*-
  3.  
  4. import threading
  5. import random
  6. import time
  7.  
  8. # Dining philosophers, 5 Phillies with 5 forks. Must have two forks to eat.
  9. #
  10. class Philosopher(threading.Thread):
  11.  
  12.     running = True
  13.     eatingPhilosophers = 0
  14.  
  15.     def __init__(self, xname, forkOnLeft, forkOnRight):
  16.         threading.Thread.__init__(self)
  17.         self.name = xname
  18.         self.forkOnLeft = forkOnLeft
  19.         self.forkOnRight = forkOnRight
  20.  
  21.     def run(self):
  22.         while(self.running):
  23.             #  Philosopher is thinking (but really is sleeping).
  24.             time.sleep( random.uniform(3,13))
  25.             print ('%s is hungry.' % self.name)
  26.             self.dine()
  27.  
  28.     def dine(self):
  29.         fork1, fork2 = self.forkOnLeft, self.forkOnRight
  30.  
  31.         while self.running:
  32.             if self.eatingPhilosophers < 5:
  33.                 fork1.acquire(True)
  34.                 self.eatingPhilosophers += 1
  35.                 fork2.acquire(True)
  36.                 break
  37.             #locked = fork2.acquire(False)
  38.             #if locked: break
  39.             #fork1.release()
  40.             #print '%s swaps forks' % self.name
  41.             #fork1, fork2 = fork2, fork1
  42.         else:
  43.             return
  44.  
  45.         self.dining()
  46.         fork2.release()
  47.         fork1.release()
  48.         Philosopher.eatingPhilosophers -= 1
  49.  
  50.  
  51.     def dining(self):
  52.         print ('%s starts eating '% self.name)
  53.         time.sleep(random.uniform(1,10))
  54.         print ('%s finishes eating and leaves to think.' % self.name)
  55.  
  56. def DiningPhilosophers():
  57.     forks = [threading.Lock() for n in range(5)]
  58.     philosopherNames = ('Aristotle','Kant','Buddha','Marx', 'Russel')
  59.  
  60.     philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \
  61.             for i in range(5)]
  62.  
  63.     random.seed(507129)
  64.     Philosopher.running = True
  65.     for p in philosophers: p.start()
  66.     time.sleep(100)
  67.     Philosopher.running = False
  68.     print ("Now we're finishing.")
  69.  
  70. DiningPhilosophers()
  71.  
RAW Paste Data