fndemers

Untitled

Jan 20th, 2021
815
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.  
  9. # Dining philosophers, 5 Phillies with 5 forks. Must have two forks to eat.
  10. #
  11. # Deadlock is avoided by never waiting for a fork while holding a fork (locked)
  12. # Procedure is to do block while waiting to get first fork, and a nonblocking
  13. # acquire of second fork.  If failed to get second fork, release first fork,
  14. # swap which fork is first and which is second and retry until getting both.
  15. #
  16.  
  17. class Philosopher(threading.Thread):
  18.  
  19.     running = True
  20.  
  21.     def __init__(self, xname, forkOnLeft, forkOnRight):
  22.         threading.Thread.__init__(self)
  23.         self.name = xname
  24.         self.forkOnLeft = forkOnLeft
  25.         self.forkOnRight = forkOnRight
  26.  
  27.     def run(self):
  28.         while(self.running):
  29.             #  Philosopher is thinking (but really is sleeping).
  30.             time.sleep( random.uniform(3,13))
  31.             print ('%s is hungry.' % self.name)
  32.             self.dine()
  33.  
  34.     def dine(self):
  35.         fork1, fork2 = self.forkOnLeft, self.forkOnRight
  36.  
  37.         while self.running:
  38.             pass
  39.             fork1.acquire(True)
  40.             locked = fork2.acquire(False)
  41.             if locked: break
  42.             fork1.release()
  43.             print ('%s swaps forks' % self.name)
  44.             fork1, fork2 = fork2, fork1
  45.         else:
  46.             return
  47.  
  48.         self.dining()
  49.         fork2.release()
  50.         fork1.release()
  51.  
  52.     def dining(self):
  53.         print ('%s starts eating '% self.name)
  54.         time.sleep(random.uniform(1,10))
  55.         print ('%s finishes eating and leaves to think.' % self.name)
  56.  
  57. def DiningPhilosophers():
  58.     forks = [threading.Lock() for n in range(5)]
  59.     philosopherNames = ('Aristotle','Kant','Buddha','Marx', 'Russel')
  60.  
  61.     philosophers= [Philosopher(philosopherNames[i], forks[i%5], forks[(i+1)%5]) \
  62.             for i in range(5)]
  63.  
  64.     random.seed(507129)
  65.     Philosopher.running = True
  66.     for p in philosophers: p.start()
  67.     time.sleep(100)
  68.     Philosopher.running = False
  69.     print ("Now we're finishing.")
  70.  
  71. DiningPhilosophers()
  72.  
RAW Paste Data