Monitor
Used to ensure safe and proper access to resources over multiple processes.
The monitor
section is an advanced effect designed to manage resources that are used across multiple processes.
Variable types are designed to be thread-safe, so that changes to their values can be seen by all threads. However, multiple processes can simultaneously try to read and modify the same data.
In this example, either of the assert
checks could fail: both processes will run simultaneously and could modify/read the atomic variable in any order.
Two possible outcomes are shown below.
This is known as a race condition: the execution order of the two processes will determine the outcome of the program.
Race conditions like these are often random and unpredictable, despite the background process usually being slower to start. Tiny variations in the soft or solid state of the machine can impact the order of outcomes.
In order to prevent this we can put a monitor on a resource that prevents other processes from accessing it until our one finishes. The monitor will also make sure any previous changes are finished and closed before our code runs.
A monitor locks a particular object, not its variable.
For example, we cannot lock a numerical variable {var} = 5
because the value 5
will change.
This can be used to create reliable programs that share resources across multiple processes.
Processes will pause until a resource is unlocked. Be careful with locking resources that are used by a sub-process since this can deadlock the program if the lock is never released.
Last updated