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.)

    We belong to the community. It is not the tailor alone who is the ninth part of a man; it is as much the preacher, and the merchant, and the farmer. Where is this division of labor to end? and what object does it finally serve? No doubt another may also think for me; but it is not therefore desirable that he should do so to the exclusion of my thinking for myself.
    Henry David Thoreau (1817–1862)