import threading
from time import sleep
fork1 = threading.Lock()
fork2 = threading.Lock()
fork3 = threading.Lock()
fork4 = threading.Lock()
fork5 = threading.Lock()
p_and_f = {
'1': (fork2, fork1),
'2': (fork3, fork2),
'3': (fork4, fork3),
'4': (fork5, fork4),
'5': (fork2, fork5)
}
def worker(self):
if p_and_f[self.name][0].locked():
print(f"philosopher {self.name} is thinking")
sleep(4)
else:
p_and_f[self.name][0].acquire()
if p_and_f[self.name][1].locked():
p_and_f[self.name][0].release()
print(f"philosopher {self.name} is thinking")
sleep(4)
else:
p_and_f[self.name][1].acquire()
print(f"philosopher {self.name} is eating")
sleep(8)
p_and_f[self.name][0].release()
p_and_f[self.name][1].release()
self.eating = True
class Philosopher(threading.Thread):
def __init__(self, eating=False, name=None, *args, **kwargs):
super().__init__(*args, **kwargs)
self.eating = eating
self.name = name
def run(self):
while True:
if self.eating:
print(f"{'*' * 20} philosopher {self.name} finished eating{'*' * 20}")
break
else:
worker(self)
if __name__ == "__main__":
threads = list()
for i in range(1, 6):
p = Philosopher(eating=False, name=str(i))
p.start()
threads.append(p)
for tr in threads:
tr.join()