Monitor (synchronization) - Mutual Exclusion

Mutual Exclusion

As a simple example, consider a monitor for performing transactions on a bank account.

monitor class Account { private int balance := 0 invariant balance >= 0 public method boolean withdraw(int amount) precondition amount >= 0 { if balance < amount then return false else { balance := balance - amount ; return true } } public method deposit(int amount) precondition amount >= 0 { balance := balance + amount } }

While a thread is executing a method of a monitor, it is said to occupy the monitor. Monitors are implemented to enforce that at each point in time, at most one thread may occupy the monitor. This is the monitor's mutual exclusion property.

Upon calling one of the methods, a thread must wait until no other thread is executing any of the monitor's methods before starting execution of its method. Note that without this mutual exclusion, in the present example, two threads could cause money to be lost or gained for no reason. For example two threads withdrawing 1000 from the account could both return true, while causing the balance to drop by only 1000, as follows: first, both threads fetch the current balance, find it greater than 1000, and subtract 1000 from it; then, both threads store the balance and return.

In a simple implementation, mutual exclusion can be implemented by the compiler equipping each monitor object with a private lock, often in the form of a semaphore. This lock, which is initially unlocked, is locked at the start of each public method, and is unlocked at each return from each public method.

Read more about this topic:  Monitor (synchronization)

Famous quotes containing the words mutual and/or exclusion:

    Nature’s law says that the strong must prevent the weak from living, but only in a newspaper article or textbook can this be packaged into a comprehensible thought. In the soup of everyday life, in the mixture of minutia from which human relations are woven, it is not a law. It is a logical incongruity when both strong and weak fall victim to their mutual relations, unconsciously subservient to some unknown guiding power that stands outside of life, irrelevant to man.
    Anton Pavlovich Chekhov (1860–1904)

    All men, in the abstract, are just and good; what hinders them, in the particular, is, the momentary predominance of the finite and individual over the general truth. The condition of our incarnation in a private self, seems to be, a perpetual tendency to prefer the private law, to obey the private impulse, to the exclusion of the law of the universal being.
    Ralph Waldo Emerson (1803–1882)