import sys sys.path.append("/usr/local/lib/python2.3/site-packages/") import random import pyipc import time import os from string import atoi # python Dining_Philosophers.py (N Philosophers) (t time in sec) if len(sys.argv) < 3 or len(sys.argv) > 3: print "Usage: python Dining_Philosophers.py N t" print "N: The number of Philosophers" print "t: Duration of program in seconds" # argv[1] is (N Philosophers) # argv[2] is (t time in sec) philosopher_N = sys.argv[1] chopstick_N = sys.argv[1] # number of philosophers = number of chopsticks time_t = sys.argv[2] children_list = [] # converts the command line arguments into integers philosopher_N = atoi(philosopher_N) chopstick_N = atoi(chopstick_N) time_t = atoi(time_t) def thinking(phil_id): print "Philosopher ", phil_id, " is thinking" random.seed() time.sleep( random.randint(1, 5) ) return def hungry(phil_id, chopsticks): print "Philosopher ", phil_id, " is hungry" chopsticks.wait(chopstick_N) if phil_id == 0: chopsticks.wait(chopstick_N - 1) #grab the left chopstick else: chopsticks.wait(phil_id - 1) # grab the left chopstick chopsticks.wait(phil_id) # grab the right chopstick chopsticks.signal(chopstick_N) return def eating(phil_id): print "Philosopher ", phil_id, " is eating" random.seed() time.sleep( random.randint(1, 5) ) if phil_id == 0: chopsticks.signal(chopstick_N - 1) else: chopsticks.signal(phil_id - 1) chopsticks.signal(phil_id) return # ----------------------------- # Creating the Chopsticks # ----------------------------- uniq_key = pyipc.ftok("Dining_Philosophers.py", 7) chopsticks = pyipc.SemaphoreGroup(uniq_key, chopstick_N + 1) # I make N + 1 semaphores because I use one extra semaphore # to prevent the situation when all the philosophers # decide to grab their left chopstick at the same time # ----------------------------- # The Birth of the Philosophers # ----------------------------- phil_id = 0 # Variable that holds a unique id for each philosopher # Sets the oldest philosopher to phil_id 0 for i in range( philosopher_N - 1 ): #this loop creates N - 1 philosophers pid = os.fork() if pid == 0: phil_id = i + 1 break else: children_list.append(pid) continue # ---------------------------- # The Philosophers live their lives # ---------------------------- total_time = time.time() + time_t while time.time() < total_time: thinking(phil_id) hungry(phil_id, chopsticks) eating(phil_id) if phil_id == 0: # oldest philosopher waits for everyone to die # and does all the cleaning up for child in children_list: os.waitpid(child, 0) pyipc.removeIPC(chopsticks)