状態に応じて処理を変えているが、これも結局、両方のスレッドが待ち状態になってしまい、ロックがかかってしまう。
一般的に、starvation(飢饉状態)という。
import time
from threading import Thread
from lock_with_name import LockWithName
dumplings = 20
class Philosopher(Thread):
def __init__(self, name: str,
left_chopstick: LockWithName,
right_chopstick: LockWithName):
super().__init__()
self.name = name
self.left_chopstick = left_chopstick
self.right_chopstick = right_chopstick
def run(self) -> None:
global dumplings
while dumplings > 0:
self.left_chopstick.acquire()
print(f"{self.left_chopstick.name} chopstick "
f"grabbed by {self.name}")
if self.right_chopstick.locked():
print(f"{self.name} can not get the "
f"{self.right_chopstick.name} chopstick, "
f"politely concedes...")
else:
self.right_chopstick.acuire()
print(f"{self.right_chopstick.name} chopstick "
f"grabbed by {self.name}")
dumplings -= 1
print(f"{self.name} eats dumpling. Dumplings "
f"left: {dumplings}")
time.sleep(1)
self.right_chopstick.release()
self.left_chopstick.release()
if __name__ == "__main__":
chopstick_a = LockWithName("chopstick_a")
chopstick_b = LockWithName("chopstick_b")
philosopher_1 = Philosopher("Philosopher #1", chopstick_a, chopstick_b)
philosopher_2 = Philosopher("Philosopher #2", chopstick_b, chopstick_a)
philosopher_1.start()
philosopher_2.start()
Philosopher #2 can not get the chopstick_a chopstick, politely concedes…
chopstick_b chopstick grabbed by Philosopher #2
Philosopher #2 can not get the chopstick_a chopstick, politely concedes…
chopstick_b chopstick grabbed by Philosopher #2
Philosopher #2 can not get the chopstick_a chopstick, politely concedes…
Philosopher #1 can not get the chopstick_b chopstick, politely concedes…
chopstick_a chopstick grabbed by Philosopher #1
Philosopher #1 can not get the chopstick_b chopstick, politely concedes…
chopstick_a chopstick grabbed by Philosopher #1
Philosopher #1 can not get the chopstick_b chopstick, politely concedes…
chopstick_a chopstick grabbed by Philosopher #1
Philosopher #1 can not get the chopstick_b chopstick, politely concedes…
chopstick_a chopsti^C
…