public class Semaphore {
private int value;
/**
* In practice, this ArrayList would be declared as
* ArrayList<Process>.
*/
public Semaphore( int value ) {
this.value = value;
/*
* In practice, this.queue would be declared with
* new ArrayList<Process>.
*/
}
/**
* In practice, the process parameter would be of type Process.
*/
public static void P
( Object process
) { this.value--;
if ( this.value < 0 ) {
// must have been 0 or less before the decrement
queue.add( process );
}
}
/**
* In practice, the process parameter would be of type Process.
*/
public static void V
( Object process
) { this.value++;
if ( this.value <= 0 ) {
// must have been negative before the increment
queue.remove( process );
// a system call I made up
System.
addToReadyQueue( process
);
}
System.
dispatch();
// dispatches the next process on the ready queue }
}
public class Dispatcher {
public static void main
( String[] args
) {
Semaphore mutex = new mutex( 1 );
// entry section
mutex.P( p1 ); // mutex.value = 0
mutex.P( p2 ); // mutex.value = -1, mutex.queue = [p2]
// critical section
System.
dispatch();
// dispatches p1, as p2 is in mutex.queue
// exit section
/*
* mutex.value = 0, so p2 is taken off mutex.queue and
* added to System.readyQueue, and the dispatcher runs
* the next process on the ready queue, which is now p2
*/
mutex.V( p1 );
/*
* mutex.value = 1, so nothing happens because
* mutex.value > 0
*/
mutex.V( p2 );
}
}
}