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:

    Rules and particular inferences alike are justified by being brought into agreement with each other. A rule is amended if it yields an inference we are unwilling to accept; an inference is rejected if it violates a rule we are unwilling to amend. The process of justification is the delicate one of making mutual adjustments between rules and accepted inferences; and in the agreement achieved lies the only justification needed for either.
    Nelson Goodman (b. 1906)

    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)