哲学家进餐
问题就在于如何避免死锁问题
那么我们至多允许四个哲学家同时去拿左边的筷子,最终保证至少有一个科学家能进餐,并且用完之后放下筷子,从而使其他的哲学家能够拿到筷子。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| from threading import Lock, Semaphore class DiningPhilosophers: def __init__(self): self.Limit = Semaphore(4) self.ForkLocks = [Lock() for _ in range(5)]
def wantsToEat(self, philosopher: int, pickLeftFork: 'Callable[[], None]', pickRightFork: 'Callable[[], None]', eat: 'Callable[[], None]', putLeftFork: 'Callable[[], None]', putRightFork: 'Callable[[], None]') -> None:
right_fork = philosopher left_fork = (philosopher + 1) % 5
self.Limit.acquire()
self.ForkLocks[right_fork].acquire() self.ForkLocks[left_fork].acquire() pickLeftFork() pickRightFork() eat() putLeftFork() putRightFork()
self.ForkLocks[right_fork].release() self.ForkLocks[left_fork].release()
self.Limit.release()
|