Mutex vs Monitor

In this lesson, let's learn what a monitor is and how it is different than a mutex. Monitors are advanced concurrency constructs and specific to language frameworks.

We'll cover the following...

Mutex vs Monitor

Continuing our discussion from the previous section on locking and signaling mechanisms, we'll now pore over an advanced concept, the monitor. Note that in the theory of operating systems, a monitor is implemented using condition variables, and a monitor can be associated with more than one condition variable. In Ruby, a monitor can be associated with multiple condition variables. However, in some languages, e.g., C# and Java, there's no type equivalent of a theoretical condition variable. Instead, every object inherently implements a condition variable. The discussion that follows isn't specific to Ruby but about the general concept of a monitor.

Concisely, a monitor is a mutex and then some. Monitors are generally language-level constructs, whereas mutex and semaphore are lower-level or OS-provided constructs.

To understand monitors, let's first see the problem they solve. Usually, in multi-threaded applications, a thread needs to wait for some program predicate to be true before it can proceed forward. Think about a producer/consumer application. If the producer hasn't produced anything, the consumer can't consume anything. So the consumer must wait on a predicate that lets the consumer know that something has indeed been produced. What could be a crude way of accomplishing this? The consumer could repeatedly check in a loop for the predicate to be set to true. The pattern would resemble the pseudocode below:

def busyWaitFunction() 
    // acquire mutex
    while predicate is false 
      // release mutex
      // acquire mutex
    end
    // do something useful
    // release mutex
end

Within the while loop, we'll first release the mutex giving other threads a chance to acquire it and set the loop predicate to true. Before we check the loop predicate again, we make sure we have acquired the mutex. ...