Jurassic Park consists of a dinosaur museum and a park for
safari riding. There are m passengers and n
single-passengers cars. Passengers wander around the museum
for a while, then line up to take a ride in a safari car.
When a car is available, it loads the one passenger it can
hold and rides around the park for a random amount of time.
If the n cars are all out riding passengers around,
then a passenger who wants to ride waits: if a car is ready
to load but there are no waiting passengers, then the car
waits. Use semaphores to synchronize the m
passengers and the n car processes.
The following code might seem to satisfy the basic
requirements. But ask yourself: which car is unloading
which passenger in the second last line of the car
run routine? This solution has a fatal (literally)
error in it! Would you ride through a park of prehistoric
carnivourous dinosaurs if you could not guarantee that the
ride would not let you out in the middle of the park?
Talk amongst yourselves to see if you can discover
the correct solution.
passReady = semaphore(0)
carAvail = semaphore(n)
unloadPass = semaphore(0)
loadPass = semaphore(0)
class passenger(Thread):
def __init__(self,pNo):
self.passengerNo=pNo
def run(self):
while True:
wander around museum
passReady.signal()
carAvail.wait()
loadPass.wait()
ride car through park
unloadPass.wait()
class car(Thread):
def __init__(self,cNo):
self.carNo=cNo
def run(self):
while True:
passReady.wait()
loadPass.signal()
travel through park
unloadPass.signal()
carAvail.signal()
passengers = [passenger(i) for i in range(m)]
cars = [cars(i) for i in range(n)]
for i in range(m):
passengers(i).start()
for i in range(n):
cars(i).start()