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

Deadlock

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

Comments