tags: synchronization multithreading multiprocessing threads process
Monitors
A monitor is an abstraction provided to implement synchronization while accessing sharing resource. It abstracts the implementation of conditional variables and semaphores or mutexes.
This is the feature provided the by language itself. It is the concept and different language implements this concept.
For instance, Java uses synchronized
keyword to achieve synchronization on the block of code or the method.
The producer and consumer problem can be thought using monitors in this way.
function Producer() {
while true {
item = produceItem()
ProducerConsumer.insert(item)
}
}
function Consumer() {
while true {
ProducerConsumer.remove()
}
}
monitor ProducerConsumer {
cond_var full, empty;
int buffer = 0;
mutex_var mutex;
function insert(item) {
lock(mutex)
if (buffer != 0) wait(full, mutex)
buffer = 1
signal(empty)
unlock(mutex)
}
function remove() {
lock(mutex)
if (buffer == 0) wait(empty, mutex)
buffer = 0
signal(full)
unlock(mutex)
}
}