Untitled
unknown
plain_text
a year ago
1.5 kB
6
Indexable
public class SafeAlley extends Alley {
private int up, down;
private final Semaphore alleySem, downSem, upSem;
protected SafeAlley() {
up = 0;
down = 0;
alleySem = new Semaphore(1);
downSem = new Semaphore(1);
upSem = new Semaphore(1);
}
/* Block until car no. may enter alley */
public void enter(int no) throws InterruptedException {
if (no < 5) { // down-going cars
downSem.P();
if (down == 0) {
alleySem.P(); // First down-going car acquires alley
}
down++;
downSem.V();
} else { // up-going cars
upSem.P();
if (up == 0) {
alleySem.P(); // First up-going car acquires alley
}
up++;
upSem.V();
}
}
/* Register that car no. has left the alley */
public void leave(int no) throws InterruptedException {
if (no < 5) { // down-going cars
downSem.P();
down--;
if (down == 0) {
alleySem.V(); // Last down-going car releases alley
}
downSem.V();
} else { // up-going cars
upSem.P();
up--;
if (up == 0) {
alleySem.V(); // Last up-going car releases alley
}
upSem.V();
}
}
}Editor is loading...
Leave a Comment