35 The roller coaster problem
This problem is from Andrews’s Concurrent Programming (Andrews 1991), but he attributes it to J. S. Herman’s Master’s thesis.
Suppose there are \(n\) passenger threads and a car thread. The passengers repeatedly wait to take rides in the car, which can hold \(C\) passengers, where \(C<n\). The car can go around the tracks only when it is full.
Here are some additional details:
Passengers should invoke
boardandunboard.The car should invoke
load,runandunload.Passengers cannot board until the car has invoked
loadThe car cannot depart until \(C\) passengers have boarded.
Passengers cannot unboard until the car has invoked
unload.
Puzzle: Write code for the passengers and car that enforces these constraints.
35.1 Roller Coaster hint
mutex protects passengers, which counts the number of passengers that have invoked board.
Passengers wait on boardQueue before boarding and unboardQueue before unboarding. allAboard indicates that the car is full.
35.2 Roller Coaster solution
Here is my code for the car thread:
When the car arrives, it signals \(C\) passengers, then waits for the last one to signal allAboard. After it departs, it allows \(C\) passengers to disembark, then waits for allAshore.
Passengers wait for the car before boarding, naturally, and wait for the car to stop before leaving. The last passenger to board signals the car and resets the passenger counter.