In computer science a monitor is also a construct used for process
synchronization (introduced by Hoare). It is a piece of code or an object which achieves
mutual exclusion on its own (of course appropriate commands have to
be inserted by e.g. the compiler). This prevents the programmer from
creating bugs by forgetting to call methods like unlock() or
semaphore.v(). Also, a monitor can have so called "condition
variables" inside it, onto which processes that entered the monitor
can wait.
It is probably the easiest to explain a monitor using a producer
consumer problem implementation in Java:
void produce()
{
for(;;)
{
// do production of x
synchronized(buffer)
{
while(buffer.full())
buffer.wait();
buffer.add(x);
buffer.notifyAll();
}
}
}
void consume()
{
for(;;)
{
synchronized(buffer)
{
while(buffer.empty())
buffer.wait();
x=buffer.removeFirst();
buffer.notifyAll();
}
// consume x
}
}
The sychronized blocks mark the code pieces which are
part of the buffer monitor. This monitor has two tasks. First, it takes care that
consumer and producer are not manipulating the buffer data structures
at the same time. Second, it allows each process to wait until a
condition becomes true (for the producer e.g.: free space in the
buffer available?). If the conditions is false, the process blocks
and other processes may enter the monitor. Once a process has
modified the state of the monitor in such a way that a condition
might have become true, it notifies all waiting processes. Those then
compete normally for the monitor since only one of them can enter.
The lucky one can continue to execute.
BTW, the above implementation is not
very efficient so don't use it in real life.(And it hasn't been checked for syntax errors at all.)