views:

224

answers:

1

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);
}
A: 

I don't see any problems... I found some general descriptions of the up/down functionality that probably apply in your case too:

down (down NUMBER)

The down method decreases the semaphore's count by the specified number, or one if no number has been specified. If the semaphore's count would drop below zero, this method will block until such time that the semaphore's count is equal to or larger than the amount you're downing the semaphore's count by.

up (up NUMBER)

The up method increases the semaphore's count by the number specified, or one if no number's been specified. This will unblock any thread blocked trying to down the semaphore if the up raises the semaphore count above what the downs are trying to decrement it by.

So when you signal up you're allowing the blocking thread to proceed. When you signal down you're going to block until up is called again.

mayBoard.up(C); <=== using this as a way of saying repeat this semaphore C times

Either I'm confused or your colleagues are confused: calling mayBoard.up(C) simply causes the semaphore to increase its count by C... I assume that C is the number of passengers that you want to allow on board. So for each passenger that boards you should call mayBoard.down(1) or mayBoard.down(). Once the count of the mayBoard semaphore is 0, the thread will block until you allow more passengers to board.

Lirik