All Topics  
Monitor (synchronization)

 

   Email Print
   Bookmark   Link






 

Monitor (synchronization)



 
 
In concurrent programming, a monitor is an object
Object (computer science)

In its simplest embodiment, an object is an allocated region of storage. Since programming languages use variable#Computer_programmings to access objects, the terms object and variable are often used interchangeably....
intended to be used safely by more than one thread
Thread (computer science)

In computer science, a thread of execution is a Fork of a computer program into two or more Concurrency running task s. The implementation of threads and process es differs from one operating system to another, but in most cases, a thread is contained inside a process....
. The defining characteristic of a monitor is that its methods are executed with mutual exclusion
Mutual exclusion

Mutual exclusion algorithms are used in concurrent programming to avoid the simultaneous use of a common resource, such as a global variable, by pieces of computer code called critical sections....
. That is, at each point in time, at most one thread
Thread (computer science)

In computer science, a thread of execution is a Fork of a computer program into two or more Concurrency running task s. The implementation of threads and process es differs from one operating system to another, but in most cases, a thread is contained inside a process....
 may be executing any of its methods
Method (computer science)

In object-oriented programming, a method is a subroutine that is exclusively associated either with a class or with an object . Like a procedure in procedural programming languages, a method usually consists of a sequence of statement to perform an action, a set of input parameter to customize those actions, and possibly an output value...
. This mutual exclusion greatly simplifies reasoning about the implementation of monitors compared with code that may be executed in parallel.

Monitors also provide a mechanism for threads
Thread (computer science)

In computer science, a thread of execution is a Fork of a computer program into two or more Concurrency running task s. The implementation of threads and process es differs from one operating system to another, but in most cases, a thread is contained inside a process....
 to temporarily give up exclusive access, in order to wait for some condition to be met, before regaining exclusive access and resuming their task.






Discussion
Ask a question about 'Monitor (synchronization)'
Start a new discussion about 'Monitor (synchronization)'
Answer questions from other users
Full Discussion Forum



Encyclopedia


In concurrent programming, a monitor is an object
Object (computer science)

In its simplest embodiment, an object is an allocated region of storage. Since programming languages use variable#Computer_programmings to access objects, the terms object and variable are often used interchangeably....
intended to be used safely by more than one thread
Thread (computer science)

In computer science, a thread of execution is a Fork of a computer program into two or more Concurrency running task s. The implementation of threads and process es differs from one operating system to another, but in most cases, a thread is contained inside a process....
. The defining characteristic of a monitor is that its methods are executed with mutual exclusion
Mutual exclusion

Mutual exclusion algorithms are used in concurrent programming to avoid the simultaneous use of a common resource, such as a global variable, by pieces of computer code called critical sections....
. That is, at each point in time, at most one thread
Thread (computer science)

In computer science, a thread of execution is a Fork of a computer program into two or more Concurrency running task s. The implementation of threads and process es differs from one operating system to another, but in most cases, a thread is contained inside a process....
 may be executing any of its methods
Method (computer science)

In object-oriented programming, a method is a subroutine that is exclusively associated either with a class or with an object . Like a procedure in procedural programming languages, a method usually consists of a sequence of statement to perform an action, a set of input parameter to customize those actions, and possibly an output value...
. This mutual exclusion greatly simplifies reasoning about the implementation of monitors compared with code that may be executed in parallel.

Monitors also provide a mechanism for threads
Thread (computer science)

In computer science, a thread of execution is a Fork of a computer program into two or more Concurrency running task s. The implementation of threads and process es differs from one operating system to another, but in most cases, a thread is contained inside a process....
 to temporarily give up exclusive access, in order to wait for some condition to be met, before regaining exclusive access and resuming their task. Monitors also have a mechanism for signaling other threads that such conditions have been met.

Monitors were invented by C.A.R. Hoare

and Per Brinch Hansen
Per Brinch Hansen

Per Brinch Hansen was a Danish-American computer scientist known for concurrent programming theory....
,

and were first implemented in Brinch Hansen's
Per Brinch Hansen

Per Brinch Hansen was a Danish-American computer scientist known for concurrent programming theory....
 Concurrent Pascal
Concurrent Pascal

Concurrent Pascal was designed by Per Brinch Hansen for writing concurrent computing programs such asoperating systems and real-time monitoring systems on shared memory...
 language.

Mutual exclusion


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

monitor class Account

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
Mutual exclusion

Mutual exclusion algorithms are used in concurrent programming to avoid the simultaneous use of a common resource, such as a global variable, by pieces of computer code called critical sections....
 property.

Upon calling one of the methods, a thread must wait until no 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 without error while causing the balance to drop by only 1000.

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
Semaphore (programming)

In computer science, a semaphore is a protected variable or abstract data type which constitutes the classic method for restricting access to shared resources such as shared memory in a multiprogramming environment....
. This lock is initially unlocked, is locked at the start of each public method, and is unlocked at each return from each public method.

Waiting and signaling


For many applications, mutual exclusion is not enough. Threads attempting an operation may need to wait until some assertion
Assertion (computing)

In computer programming, an assertion is a First-order logic placed in a program to indicate that the developer thinks that the predicate is always true at that place....
  holds true. A busy waiting
Busy waiting

In software engineering, busy waiting or spinning is a technique in which a process repeatedly checks to see if a condition is true, such as waiting for Computer keyboard input or waiting for a lock to become available....
 loop

while not( ) do skip

will not work, as mutual exclusion will prevent any other thread from entering the monitor to make the condition true.

The solution is condition variables. Conceptually a condition variable is a queue of threads, associated with a monitor, upon which a thread may wait for some assertion to become true. Thus each condition variable is associated with some assertion . While a thread is waiting upon a condition variable, that thread is not considered to occupy the monitor, and so other threads may enter the monitor to changes the monitor's state. In most types of monitors, these other threads may signal the condition variable to indicate that assertion is true.

Thus there are two main operations on conditions variables:
  • wait c is called by a thread that needs to wait until the assertion to be true before proceeding.
  • signal c (sometimes written as notify c) is called by a thread to indicate that the assertion is true.


As an example, consider a monitor that implements a semaphore
Semaphore (programming)

In computer science, a semaphore is a protected variable or abstract data type which constitutes the classic method for restricting access to shared resources such as shared memory in a multiprogramming environment....
. There are methods to increment (V) and to decrement (P) a private integer s. However, the integer must never be decremented below 0; thus a thread that tries to decrement must wait until the integer is positive. We use a condition variable sIsPositive with an associated assertion of .

monitor class Semaphore

When a signal happens on a condition that at least one other thread is waiting on, there are at least two threads that could then occupy the monitor: the thread that signals and any one of the threads that is waiting. In order that at most one thread occupies the monitor at each time, a choice must be made. Two schools of thought exist on how best to resolve this choice. This leads to two kinds of condition variables which will be examined next:
  • Blocking condition variables give priority to a signaled thread.
  • Nonblocking condition variables give priority to the signaling thread.


Blocking condition variables


The original proposals by C.A.R. Hoare and Per Brinch Hansen
Per Brinch Hansen

Per Brinch Hansen was a Danish-American computer scientist known for concurrent programming theory....
 were for blocking condition variables. Monitors using blocking condition variables are often called Hoare style monitors. With a blocking condition variable, the signaling thread must wait outside the monitor (at least) until the signaled thread relinquishes occupancy of the monitor by either returning or by again waiting on a condition.

We assume there are two queues of threads associated with each monitor object
  • e is the entrance queue
  • s is a queue of threads that have signaled.
In addition we assume that for each condition , there is a queue
  • .q, which is a queue for threads waiting on condition
All queues are typically guaranteed to be fair (i.e. each thread that enters the queue will not be not chosen an infinite number of times) and, in some implementations, may be guaranteed to be first in first out.

The implementation of each operation is as follows. (We assume that each operation runs in mutual exclusion to the others; thus restarted threads do not begin executing until the operation is complete.)

enter the monitor: enter the method if the monitor is locked add this thread to e block this thread else lock the monitor

leave the monitor: schedule return from the method

wait : add this thread to .q schedule block this thread

signal : if there is a thread waiting on .q select and remove one such thread t from .q (t is called "the signaled thread") add this thread to s restart t (so t will occupy the monitor next) block this thread

schedule : if there is a thread on s select and remove one thread from s and restart it (this thread will occupy the monitor next) else if there is a thread on e select and remove one thread from e and restart it (this thread will occupy the monitor next) else unlock the monitor (the monitor will become unoccupied)

The schedule routine selects the next thread to occupy the monitor or, in the absence of any candidate threads, unlocks the monitor.

The resulting signaling discipline is known a "signal and urgent wait," as the signaler must wait, but is given priority over threads on the entrance queue. An alternative is "signal and wait," in which there is no s queue and signaler waits on the e queue instead.

Some implementations provide a signal and return operation that combines signaling with returning from a procedure.

signal and return : if there is a thread waiting on .q select and remove one such thread t from .q (t is called "the signaled thread") restart t (so t will occupy the monitor next) else schedule return from the method

In either case ("signal and urgent wait" or "signal and wait"), when a condition is signaled and there is at least one thread on waiting on the condition, the signaling thread hands occupancy over to the signaled thread seamlessly, so that no other thread can gain occupancy in between. If is true at the start of each signal operation, it will be true at the end of each wait operation. This is summarized by the following contracts
Design by contract

Design by Contract or Programming by Contract is an approach to designing computer software. It prescribes that software designers should define Formal methods, precise and verifiable interface specifications for Component-based software engineering#Software component based upon the theory of abstract data types and the conceptual metaph...
. In these contracts, is the monitor's invariant
Invariant (computer science)

In Computer science, a predicate that, if true, will remain true throughout a specific sequence of Operation , is called invariant to that sequence....
.

enter the monitor: postcondition

leave the monitor: precondition

wait : precondition modifies the state of the monitor postcondition and

signal : precondition and modifies the state of the monitor postcondition

signal and return : precondition and

In these contracts, it is assumed that and do not depend on the contents or lengths of any queues.

(When the condition variable can be queried as to the number of threads waiting on its queue, more sophisticated contracts can be given. For example, a useful pair of contracts, allowing occupancy to be passed without establishing the invariant, is

wait : precondition modifies the state of the monitor postcondition

signal precondition (not empty and ) or (empty and ) modifies the state of the monitor postcondition

See Howard and Buhr et al, for more).

It is important to note here that the assertion is entirely up to the programmer; he or she simply needs to be consistent about what it is.

We conclude this section with an example of a blocking monitor that implements a bounded, thread-safe stack
Stack (data structure)

In computer science, a stack is an abstract data type and data structure based on the principle of LIFO . Stacks are used extensively at every level of a modern computer system....
.

monitor class SharedStack

Nonblocking condition variables


With nonblocking condition variables (also called "Mesa style" condition variables or "signal and continue" condition variables), signaling does not cause the signaling thread to lose occupancy of the monitor. Instead the signaled threads are moved to the e queue. There is no need for the s queue.

With nonblocking condition variables, the signal operation is often called notify — a terminology we will follow here. It is also common to provide a notify all operation that moves all threads waiting on a condition to the e queue.

The meaning of various operations are given here. (We assume that each operation runs in mutual exclusion to the others; thus restarted threads do not begin executing until the operation is complete.)

enter the monitor: enter the method if the monitor is locked add this thread to e block this thread else lock the monitor leave the monitor: schedule return from the method

wait : add this thread to .q schedule block this thread

notify : if there is a thread waiting on .q select and remove one thread t from .q (t is called "the notified thread") move t to e

notify all : move all threads waiting on .q to e

schedule : if there is a thread on e select and remove one thread from e and restart it else unlock the monitor

As a variation on this scheme, the notified thread may by moved to a queue called w, which has priority over e. See Howard and Buhr et al. for further discussion.

It is possible to associate an assertion with each condition variable such that is sure to be true upon return from wait . However, one must ensure that is preserved from the time the notifying thread gives up occupancy until the notified thread is selected to re-enter the monitor. Between these times there could be activity by other occupants. Thus is is common for to simply be true.

For this reason, it is usually necessary to enclose each wait operation in a loop like this

while not( ) do wait c

where is some assertion stronger than . The operations notify and notify all operations are treated as "hints" that may be true for some waiting thread. Every iteration of such a loop past the first represents a lost notification; thus with nonblocking monitors, one must be careful to ensure that too many notifications can not be lost.

As an example of "hinting" consider a bank account in which a withdrawing thread will wait until the account has sufficient funds before proceeding

monitor class Account

In this example, the assertion being waited for is a function of the amount to be withdrawn, so it is impossible for a depositing thread to be sure that it has established the assertion. It makes sense in this case to allow each waiting thread into the monitor (one at a time) to check if itsassertion is true.

Implicit condition monitors


In the Java programming language each object may be used as a monitor. (However, methods that require mutual exclusion must be explicitly marked as synchronized). Rather than having explicit condition variables, each monitor (i.e. object) is equipped with a single wait queue, in addition to its entrance queue. All waiting is done on this single wait queue and all notify and notify all operations apply to this queue.

This approach has also been adopted in other languages such as C#
C Sharp

C# is a multi-paradigm programming language that encompasses Functional programming, Imperative programming, Generic programming, Object-oriented programming , and Component-based software engineering programming disciplines....
.

Implicit signaling


Another approach to signaling is to omit the signal operation. Whenever a thread leaves the monitor (by returning or waiting) the assertions of all waiting threads are evaluated until one is found to be true. In such a system, condition variables are not needed, but the assertions must be explicitly coded. The contract for wait is

wait : precondition modifies the state of the monitor postcondition and

History


C. A. R. Hoare
C. A. R. Hoare

Sir Charles Antony Richard Hoare , commonly known as Tony Hoare or C.A.R. Hoare, is a United Kingdom computer science, probably best known for the development in 1960 of Quicksort , one of the world's most widely used sorting algorithms....
 and Per Brinch Hansen
Per Brinch Hansen

Per Brinch Hansen was a Danish-American computer scientist known for concurrent programming theory....
 developed the idea of monitors around 1972, based on earlier ideas of their own and of E. W. Dijkstra.

Brinch Hansen was the first to implement monitors. Hoare developed the theoretical framework and demonstrated their equivalence to semaphores
Semaphore (programming)

In computer science, a semaphore is a protected variable or abstract data type which constitutes the classic method for restricting access to shared resources such as shared memory in a multiprogramming environment....
.

Monitors were soon used to structure inter-process communication
Inter-process communication

Inter-Process Communication is a set of techniques for the exchange of data among multiple thread in one or more Process . Processes may be running on one or more computers connected by a computer network....
 in the Solo Operating System.

Programming languages that have supported monitors include
  • Ada
    Ada (programming language)

    Ada is a structured programming, statically typed, Imperative programming, and Object-oriented programming high-level language computer programming programming language, extended from Pascal and other languages....
     2005 (as protected objects)
  • C# (and other languages that use the .NET Framework
    .NET Framework

    The Microsoft .NET Framework is a software framework that is available with several Microsoft Windows operating systems. It includes a large Library of coded solutions to prevent common programming problems and a virtual machine that manages the execution of programs written specifically for the Software framework....
    )
  • Concurrent Euclid
    Concurrent Euclid (programming language)

    Concurrent Euclid is a concurrent descendant of the Euclid programming language designed by James Cordy and Ric Holt, then at the University of Toronto, in 1980....
  • Concurrent Pascal
    Concurrent Pascal

    Concurrent Pascal was designed by Per Brinch Hansen for writing concurrent computing programs such asoperating systems and real-time monitoring systems on shared memory...
  • D programming language
  • Java
    Java (programming language)

    Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java ....
     (via the synchronized keyword)
  • Mesa
    Mesa programming language

    Mesa was an innovative computer programming programming language developed at PARC in the late 1970s . The language was named after the mesas of the American Southwest, referring to its design intent to be a high-level programming language....
  • Modula-3
    Modula-3

    In Computer science, Modula-3 is a programming language conceived as a successor to an upgraded version of Modula-2. While it has been influential in research circles it has not been adopted widely in industry....
  • Ruby
    Ruby (programming language)

    Ruby is a dynamic programming language, reflection , general purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features....
  • Squeak Smalltalk
    Squeak

    The Squeak programming language is a Smalltalk implementation, derived directly from Smalltalk-80 by a group at Apple Computer that included some of the original Smalltalk-80 developers....
  • Turing, Turing+
    Turing Plus (programming language)

    Turing+ is a concurrent systems programming language based the Turing programming language designed by James Cordy and Ric Holt, then at the University of Toronto, in 1987....
    , and Object-Oriented Turing
    Object-Oriented Turing

    Object-Oriented Turing is an extension of the Turing programming language programming language and a replacement for Turing Plus created by Ric Holt of the University of Toronto in 1991....
  • µC++


A number of libraries have been written that allow monitors to be constructed in languages that do not support them natively. When library calls are used, it is up to the programmer to explicitly mark the start and end of code executed with mutual exclusion. PThreads
POSIX Threads

POSIX Threads, or Pthreads, is a POSIX standard for thread s. The standard defines an Application programming interface for creating and manipulating threads....
 is one such library.

See also

  • Mutual exclusion
    Mutual exclusion

    Mutual exclusion algorithms are used in concurrent programming to avoid the simultaneous use of a common resource, such as a global variable, by pieces of computer code called critical sections....
  • Communicating sequential processes
    Communicating sequential processes

    In computer science, Communicating Sequential Processes is a specification language for describing patterns of interaction in concurrent systems....
     - a later development of monitors by C. A. R. Hoare
    C. A. R. Hoare

    Sir Charles Antony Richard Hoare , commonly known as Tony Hoare or C.A.R. Hoare, is a United Kingdom computer science, probably best known for the development in 1960 of Quicksort , one of the world's most widely used sorting algorithms....
  • Semaphore (programming)
    Semaphore (programming)

    In computer science, a semaphore is a protected variable or abstract data type which constitutes the classic method for restricting access to shared resources such as shared memory in a multiprogramming environment....


Bibliography

  • Monitors: an operating system structuring concept, C. A. R. Hoare - Communications of the ACM, v.17 n.10, p.549-557, Oct. 1974
  • Monitor classification P.A. Buhr, M. Fortier, M.H. Coffin - ACM Computing Surveys (CSUR), 1995


External links

  • "" by Charles Antony Richard Hoare
  • "" by John H. Howard (Computer Scientist)
  • "" by John H. Howard (Computer Scientist)
  • "" by Butler W. Lampson and David D. Redell
  • - description from the Open Group Base Specifications Issue 6, IEEE Std 1003.1
  • "" by Dave Marshall (Computer Scientist)
  • "" by Douglas C. Schmidt and Irfan Pyarali
  • from the Apache Portable Runtime
    Apache Portable Runtime

    The Apache Portable Runtime is a supporting library for the Apache HTTP Server web server. It provides a set of APIs that map to the underlying operating system....
     Library
  • - Perl extension for sharing data structures between threads