Monitor class
A monitor class is a kind of class (see Classes)
that guarantees exclusive access to methods of its object.
This provides another mechanism for synchronization of concurrent tasks
(for more see Concurrent expressions).
Monitor class is declared by putting word
Example:
For a fixed object of monitor class, when many threads invoke a method of this object at the same time,
then only one of them will be selected for code execution, and rest will be stopped until it is completed,
and then another one will be waked up to execute called method, and so on.
It is not deterministically specified which one of sleeping threads will be waked next,
and it will be randomly selected.
That mechanism is called an object lock or monitor lock, and the threads are waiting on that monitor lock
to exclusively execute object's methods.
Each object of monitor class has own lock (which is assigned to the object, not to class).
Enter and leave sections
Instruction
Instruction
Example:
The threads may be suspended until monitor lock is free to acquire,
on the beginning of instruction
Every method of monitor class, by default, acquire monitor lock to execute its code,
except when a methods declaration is preceded by the keyword
Example:
Only methods of the class acquire monitor lock.
But it is possible to grab monitor lock inside any other code of the class,
by using
For example:
whereever function
Conditions
A condition is a synchronization construct that allows threads to wait
until a certain condtion is met.
When a thread waits on some condition and it own a monitor lock, then it temporarily releases the lock
for the sleeping time, allowing other threads to own the lock. And when condition is met,
it will not be waked until it grabs the lock again.
Declaration of conditions inside monitor class starts with word
There are three instructions to work with condition:
Example:
Semaphore implementation
Example of basic semaphore implementation using monitor class: