# Monitors

A problem with semaphores is that they are used both to implement **mutual exclusion** and to **synchronize** processes.

Being low level primitives, they are applied in a **bottom-up** perspective.

* if required conditions are not satisfied, processes are **blocked before** they enter their **critical sections**.
* this approach is prone to errors, mainly in complex situations, as synchronization points can be scattered throughout the program.

A higher level approach should follow a **top-down** perspective.

* processes must **first enter their critical sections** and then **block if** continuation **conditions are not satisfied**.

A solution is to introduce a (concurrent) construction at the programming level that deals with mutual exclusion and synchronization separately.

A **monitor** is a synchronization mechanism, independently proposed by Hoare and Brinch Hansen, supported by a (concurrent) programming language.

The *pthread* library provides primitives that allows to implement monitors (of the Lampson-Redell type).

## Definition

<figure><img src="https://933056030-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmDWmJ4LyRblScRPGY3di%2Fuploads%2Feo8rY4EjzlsoOiq0wmRh%2Fa.png?alt=media&#x26;token=397e7474-513a-4819-936d-4ea7e74478c8" alt=""><figcaption></figcaption></figure>

An application is seen as a set of threads that compete to access the **shared data** structure.

This shared data can only be accessed through the access methods.

Every method is executed in **mutual exclusion**.

If a thread calls an access method while another thread is inside another access method, its execution is blocked until the other leaves.

Synchronization between threads is possible through **condition variables**.

Two operation on them are possible:

* **wait** – the thread is blocked and put outside the monitor.
* **signal** – if there are threads blocked, one is waked up.

## Bounded-buffer problem – solving using monitors

<figure><img src="https://933056030-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FmDWmJ4LyRblScRPGY3di%2Fuploads%2FcVe1Q5oJCS3kRAQEALO3%2Fa.png?alt=media&#x26;token=59883c2b-26ee-4569-88a3-a117a1f116c5" alt=""><figcaption></figcaption></figure>

The **mutex** is the resource used to control mutual exclusion.

**Critical sections** are explicitly framed by the **lock** and **unlock** of a mutex.
