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:

    Then, anger
    was a crease in the brow
    and silence
    a catastrophe.
    Then, making up
    was a mutual smile
    and a glance
    a gift.
    Now, just look at this mess
    that you’ve made of that love.
    You grovel at my feet
    and I berate you
    and can’t let my anger go.
    Amaru (c. seventh century A.D.)

    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)