Monitor
Definition1
由于信号量和互斥锁可能会导致**死锁(deadlock)**问题,因此,在实际生产中使用信号量和互斥锁必须非常小心。
为此,Brinch Hansen 和 Hoare 提出了一个更高层(higher-level)的同步原语(primitive),以实现互斥(mutual exclusion),称为管程(Monitor)。管程(Monitor) 从本质来说是一个程序集、变量和数据结构集合。
管程要求:在任一时刻只有一个进程能在管程中处于活跃状态(active)。
具体来说,当一个进程调用管程程序时, 管程程序会首先检查当前是否有其他进程在监视器中处于活跃状态。如果有,这个进程会进入阻塞状态直到其他进程离开了监视器;如果没有其他进程正在使用监视器,这个进程就可以使用监视器。
编译器会具体负责管程机制如何具体实现(虽然通常的方法是通过互斥锁)。因此,对程序员而言,我们只需要知道管程机制能够保证互斥访问(mutual exclusion),即任一时刻只会有一个进程进入临界区。
Definition2
In concurrent programming (also known as parallel programming), a monitor is a synchronization construct that allows threads to have both mutual exclusion and the ability to wait (block) for a certain condition to become false.
Monitors also have a mechanism for signaling other threads that their condition has been met. A monitor consists of a mutex (lock) object and condition variables. A condition variable essentially is a container of threads that are waiting for a certain condition. Monitors provide a mechanism for threads to temporarily give up exclusive access in order to wait for some condition to be met, before regaining exclusive access and resuming their task.
Another definition of monitor is a thread-safe class, object, or module that wraps around a mutex in order to safely allow access to a method or variable by more than one thread.
The defining characteristic of a monitor is that its methods are executed with mutual exclusion: At each point in time, at most one thread may be executing any of its methods. By using one or more condition variables it can also provide the ability for threads to wait on a certain condition (thus using the above definition of a “monitor”). For the rest of this article, this sense of “monitor” will be referred to as a “thread-safe object/class/module”.
Example
Java 对管程的支持
通过在方法声明(method declaration)中添加 synchronized
关键字,JVM 会保证当任何一个线程执行这个方法时,其他线程不能同时执行这个 synchronized 方法。
与经典的管程有所区别的是,Java 的 synchronized 方法不存在条件变量(condition variables)。作为代替,Java 提供了 wait
和 notify
方法,以在 synchronized 方法中使用,这分别对应 sleep
和 wakeup
方法。
Reference
- https://en.wikipedia.org/wiki/Monitor_(synchronization)
- https://courses.cs.vt.edu/~cs5204/fall99/monitor.html
- https://www.cs.princeton.edu/courses/archive/fall09/cos318/lectures/SemaphoresMonitors.pdf