Implementing a Monitor

CONTROL VARIABLES:

	mutex: semaphore, initial value 1 (FREE)
	next: record, with 2 fields:
		next.sem: semaphore, initial value 0
		next.count: counter, initial value 0

	FOR EACH CONDITION x:
	
	x: record, with 2 fields:
		x.sem: semaphore, initial value 0
		x.count: counter, initial value 0

ENTRY PROTOCOL (at the beginning of each monitor function):

	/* wait for exclusive access to the monitor */
	P(mutex);

EXIT PROTOCOL (at the end of each monitor function):

	/* if there are processes in the "next" queue, release one */
	if (next.count > 0) V(next.sem);

	/* otherwise, release the monitor */
	else V(mutex);

WAIT ON CONDITION x (x.wait):

	/* first perform the exit protocol */
	if (next.count > 0) V(next.sem);
	else V(mutex);

	/* now wait on the condition queue */
	x.count++;
	P(x.sem);
	x.count--;

SIGNAL CONDITION x (x.signal):

	/* do nothing unless a process is waiting */
	if (x.count > 0) {

		/* release the next waiting process */
		V(x.sem);

		/* wait on the "next" queue */
		next.count++;
		P(next.sem);
		next.count--;
	}