Advertisement
pasholnahuy

Untitled

Dec 23rd, 2023
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. import asyncio
  2. import threading
  3. import time
  4. import random
  5.  
  6. num_philosophers = 7
  7.  
  8. class Dinner:
  9. def __init__(self, num_philosophers):
  10. self.forks = [threading.Lock() for i in range(num_philosophers)]
  11. self.counts = [0 for i in range(num_philosophers)]
  12.  
  13.  
  14. def finished(self):
  15. if all([i >= 5 for i in self.counts]):
  16. return True
  17. return False
  18.  
  19.  
  20. @staticmethod
  21. def think():
  22. # Подумали случайное время, это может быть полезно менять в рамках самотестирования
  23. time.sleep(0.15 * random.random())
  24.  
  25. @staticmethod
  26. def eat():
  27. # Покушали случайное время, это может быть полезно менять в рамках самотестирования
  28. time.sleep(0.25 * random.random())
  29.  
  30.  
  31. def philosopher(self, i):
  32. i -= 1
  33. while not self.finished():
  34. if i % 2 == 0:
  35. self.forks[i].acquire()
  36. self.forks[(i+1) % num_philosophers].acquire()
  37. self.eat()
  38. self.counts[i] += 1
  39. self.forks[i].release()
  40. self.forks[(i+1) % num_philosophers].release()
  41.  
  42. else:
  43. self.forks[(i+1) % num_philosophers].acquire()
  44. self.forks[i].acquire()
  45. self.eat()
  46. self.counts[i] += 1
  47. self.forks[i].release()
  48. self.forks[(i+1) % num_philosophers].release()
  49.  
  50.  
  51.  
  52.  
  53.  
  54.  
  55.  
  56. dinner = Dinner(num_philosophers)
  57. philosophers = [threading.Thread(target=dinner.philosopher, args=(i,)) for i in range(num_philosophers)]
  58. for p in philosophers:
  59. p.start()
  60. for p in philosophers:
  61. p.join()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement