Advertisement
Guest User

fil

a guest
Feb 27th, 2020
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.12 KB | None | 0 0
  1. from threading import Thread, Lock, Semaphore
  2. import time
  3. import sys
  4.  
  5.  
  6.  
  7. class Philosoph(Thread):
  8. def __init__(self, leftlock, rightlock, i):
  9. Thread.__init__(self)
  10. self.leftLock = leftlock
  11. self.rightLock= rightlock
  12. self.index = i
  13.  
  14. def run(self):
  15. s.acquire()
  16. self.leftLock.acquire()
  17. self.rightLock.acquire()
  18. print('I am philosopher %s and I am eating-thinking' % self.index)
  19. self.leftLock.release()
  20. self.rightLock.release()
  21. print('I am philosopher %s and I finised and released the chopsticks' % self.index)
  22. s.release()
  23.  
  24. SIZE = 6
  25. philosophers = []
  26. locks = []
  27.  
  28. s = Semaphore(SIZE - 1)
  29.  
  30. for i in xrange(SIZE):
  31. lock = Lock()
  32. locks.append(lock)
  33.  
  34. for i in xrange(SIZE - 1):
  35. philosopher = Philosoph(locks[i % SIZE], locks[(i + 1) % SIZE], i)
  36. philosophers.append(philosopher)
  37.  
  38. philosopher = Philosoph(locks[0], locks[SIZE - 1], SIZE - 1)
  39. philosophers.append(philosopher)
  40.  
  41. for i in xrange(SIZE):
  42. philosophers[i].start()
  43.  
  44. for i in xrange(len(philosophers)):
  45. philosophers[i].join()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement