// Reference solution to the National Park Example // How to use Semaphore // by Hui Jiang int nFullCars = 0 ; // number of full cars int CurrentCar ; // the current loading car Semaphore mutex = 1 ; // exclusive access to nFullCars Semaphore AnoCarLoading = 1 ; // 0 --> another car is loading Semaphore CarReady = 0 ; // a car is ready to load Semaphore VisitorReady = 0 ; // a visitor ready to ride Semaphore RideOver[M] = 0 ; // synchronization signal for each car // to finish riding and exit safely Process Visitor(i) { int myCar ; ... walk_around_musuem() ... wait(CarReady) ; // wait for a car myCar = CurrentCar ; // get the car number for this visitor wait(mutex) ; nFullCars ++ ; signal(mutex) ; signal(VisitorReady) ; // notify a visitor ready to ride ... ride_around_park() ... wait(mutex) ; // exit from the car nFullCars --; // free a car signal(mutex) ; signal(RideOver[myCar]) ; } Process Car(j) { while(1) { wait(AnoCarLoading) ; // Wait if there is another car loading CurrentCar = j ; // no need to protect CurrentCar // since always one process access CurrentCar signal(CarReady) ; // notify a car is ready wait(VisitorReady) ; // wait for a visitor signal(AnoCarLoading) ; // Loading finished ... ride_around_park() ... wait(RideOver[j]) ; } } Process Observer { while(1) { ... sleep for a while ... wait(mutex) ; printf("nFullCars = %d\n", nFullCars) ; signal(mutex) ; } }