Semaphore vs Monitor
Semaphore is a data structure that is used to make sure that multiple processes do not access a common resource or a critical section at the same time, in parallel programming environments. Semaphores are used to avoid dead locks and race conditions. Monitor is a programming language construct that is also used to avoid multiple processes accessing a common resource at the same time therefore guarantees mutual exclusion. Monitors use conditional variables to achieve this task.
What is a Semaphore?
Semaphore is a data structure that is used to provide mutual exclusion to critical sections. Semaphores mainly support two operations called wait (historically known as P) and signal (historically known as V). The wait operation blocks a process until the semaphore is open and the signal operation allows another process (thread) to enter. Each semaphore is associated with a queue of waiting processes. When the wait operation is called by a thread, if the semaphore is open, the thread can continue. If the semaphore is closed when the wait operation is called by a thread, the thread is blocked and it has to wait in the queue. The signal operation opens a semaphore and if there is a thread already waiting in the queue, that process is allowed to proceed and if there are no threads waiting in the queue the signal is remembered for the next threads. There are two types of semaphores called mutex semaphores and counting semaphores. Mutex semaphores allow a single access to a resource and counting semaphores allow multiple threads to access a resource (which has several units available).
What is a Monitor?
A monitor is a programming language construct that is used to control access to shared data. Monitors encapsulate shared data structures, procedures (that operate on shared data structures) and synchronization between concurrent procedure invocations. A monitor makes sure that its data is not faced with unstructured accesses and guarantees that treads (which access monitor’s data through its procedures) interact in a legitimate manner. A monitor guarantees mutual exclusion by allowing only one thread to execute any monitor procedure at a given time. If another thread tries to invoke a method in the monitor, while a thread is already executing a procedure in the monitor, then the second procedure is blocked and it has to wait in the queue. There are two types of monitors named Hoare monitors and Mesa monitors. They mainly differ in their scheduling semantics.
What is the difference between Semaphore and Monitor?
尽管信号量和监视器都用于在平行编程环境中实现相互排除,但它们在实现此任务的技术方面有所不同。在监视器中,用于实现相互排除的代码位于一个位置并且更结构化,而信号量的代码则以等待和信号函数调用分布。另外,实施信号量时犯错很容易,而在实施监视器时几乎没有机会犯错误。此外,监视器使用条件变量,而信号量则不使用。
艾达says
Well described