import threading
import time
import random
class Fork:
def __init__(self, id):
self.id = id
self.lock = threading.Lock()
def acquire(self):
return self.lock.acquire(blocking=False)
def getId(self):
return self.id
def release(self):
self.lock.release()
class Philosopher(threading.Thread):
def __init__(self, id, left_fork, right_fork):
threading.Thread.__init__(self)
self.id = id
self.left_fork = left_fork
self.right_fork = right_fork
self.eat_count = 0
self.max_eat_count = 1
def __str__(self):
return (f"Philosopher({self.id},"
f" {self.right_fork.getId()}, {self.left_fork.getId()})")
def run(self):
while self.eat_count < self.max_eat_count:
# start = time.time()
print(f"Philosopher{self.id} is thinking in {time.time()}")
time.sleep(random.uniform(1, 2)) # Thinking
print(f"Philosopher{self.id} thought in {time.time() }")
self.eat()
def eat(self):
# Try to acquire both forks
while True:
if self.left_fork.acquire():
if self.right_fork.acquire():
break
else:
self.left_fork.release()
else:
continue
# start = time.time()
print(f"Philosopher {self.id} is eating Spaghetti in {time.time()}.")
time.sleep(random.uniform(1, 3))
self.left_fork.release()
self.right_fork.release()
self.eat_count += 1
print(f"Philosopher {self.id} finished eating Spaghetti in{time.time()}.")
def main():
num_philosophers = 5
forks = [Fork(i) for i in range(num_philosophers)]
philosophers = [Philosopher(i, forks[i],
forks[(i + 1) % num_philosophers])
for i in range(num_philosophers)]
# for pil in philosophers:
# print(pil.__str__())
print("start Program")
for philosopher in philosophers:
philosopher.start()
for philosopher in philosophers:
philosopher.join()
print("finished Program")
if __name__ == "__main__":
main()