Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import asyncio
- import threading
- import time
- import random
- num_philosophers = 6
- class Dinner:
- def __init__(self, num_philosophers):
- self.forks = [threading.Lock() for i in range(num_philosophers)]
- self.counts = [0 for i in range(num_philosophers)]
- def finished(self):
- if all([i >= 5 for i in self.counts]):
- return True
- return False
- @staticmethod
- def think():
- # Подумали случайное время, это может быть полезно менять в рамках самотестирования
- time.sleep(0.15 * random.random())
- @staticmethod
- def eat():
- # Покушали случайное время, это может быть полезно менять в рамках самотестирования
- time.sleep(0.25 * random.random())
- def philosopher(self, i):
- while not self.finished():
- if i % 2 == 0:
- while self.forks[i].locked():
- self.think()
- self.forks[i].acquire()
- while self.forks[(i + 1) % num_philosophers].locked():
- self.think()
- self.forks[(i+1) % num_philosophers].acquire()
- self.eat()
- self.counts[i] += 1
- self.forks[i].release()
- self.forks[(i+1) % num_philosophers].release()
- else:
- while self.forks[(i + 1) % num_philosophers].locked():
- self.think()
- self.forks[(i+1) % num_philosophers].acquire()
- while self.forks[i].locked():
- self.think()
- self.forks[i].acquire()
- self.eat()
- self.counts[i] += 1
- self.forks[i].release()
- self.forks[(i+1) % num_philosophers].release()
- dinner = Dinner(num_philosophers)
- philosophers = [threading.Thread(target=dinner.philosopher, args=(i,)) for i in range(num_philosophers)]
- for p in philosophers:
- p.start()
- for p in philosophers:
- p.join()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement