Senate Bus Problem


Problem Description

Riders come to a bus stop and wait for a bus. When the bus arrives, all the waiting riders invoke boardBus, but anyone who arrives while the bus is boarding has to wait for the next bus. The capacity of the bus is 50 people; if there are more than 50 people waiting, some will have to wait for the next bus. When all the waiting riders have boarded, the bus can invoke depart. If the bus arrives when there are no riders, it should depart immediately.

Solution

public void busAction() throws InterruptedException {

// acquire the lock so that any riders can't enter the waiting area
mutexWaitingArea.acquire();
if (waitingRiders > 0) {
// if there are riders waiting signal the bus to wait
busWaiting.release();
// wait till all the riders get in to bus
// lock can be acquired only if a rider release it signaling all the
// riders has got in
allAboard.acquire();
}
depart();

// release the lock on waiting area so others can enter
mutexWaitingArea.release();

}

 

public void busAction() throws InterruptedException {

// acquire the lock so that any riders can't enter the waiting area
mutexWaitingArea.acquire();

currentBus = Thread.currentThread();

if (waitingRiders > 0) {
// if there are riders waiting signal the bus to wait
busWaiting.release();
// wait till all the riders get in to bus
// lock can be acquired only if a rider release it signaling all the
// riders has got in
allAboard.acquire();
}
depart();

// release the lock on waiting area so others can enter
mutexWaitingArea.release();

}

The full solution along with a simulation can be found at “full solution in github

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s