Ferryboats go back and forth, carrying passengers from one side of the canal to the other. Each boat can hold at most C passengers. The passengers wait for the boats to ferry them across the canal. A boat can start crossing the river only when it is full. A boat cannot start loading passengers on one side of the canal if another boat is already loading passengers on the same side.
² Passengers should invoke board and unboard.
² Boats should invoke load, cross, and unload.
² Passengers cannot board until a boat has invoked load.
² Passengers cannot unboard until the boat has invoked unload.
- There is N boats
Using semaphores, write code for the passengers and boats that enforces these constraints.
here is what i did:
Declarations:
semaphore mayBoard(0);
semaphore allAboard(0);
semaphore mayUnboard(0);
semaphore allAshore(0);
Boat thread:
while (true) {
load();
mayBoard.up(C); // signal C passengers that they may board
allAboard.down(C); // wait until all passengers have boarded
cross();
unload();
mayUnboard.up(C); // signal C passengers to unboard
allAshore.down(C); // wait until all passengers have unboarded
}
Passenger thread:
while (true) {
mayBoard.down();
board();
allAboard.up(N);
// ferry
mayUnboard.down();
unboard();
allAshore.up(N);
}