Sub topic 15
Monitors and Condition Variables
This chapter assumes you know the semaphore wait and signal operations, the producer-consumer bounded buffer, and the idea of a mutex lock. It also assumes you can read C and pthreads-style calls. Here you will see why semaphores are error-prone, how a monitor packages mutual exclusion with waiting, and how that differs from a semaphore. Conveniently for GATE, the differences are exactly what questions test.
Why semaphores are not enough
A semaphore is a low-level tool. Correctness depends on every programmer calling wait and signal in the right order, in every routine that touches the shared data. Three typical mistakes are:
- Swapping
wait(empty)andwait(mutex)in the producer, which can deadlock. - Forgetting a
signal(mutex), which blocks all later threads. - Calling
signal(mutex)beforewait(mutex), which lets two threads into the critical section.
The compiler cannot detect any of these. A monitor moves the locking out of the programmer's hands and into the language or library structure.
What a monitor is
A monitor is a module that groups shared data with the procedures that operate on it. It has these properties:
- The shared data is private. It can only be reached through the monitor's procedures.
- At most one thread is active inside the monitor at a time. Entry and exit take and release an implicit lock.
- Threads that cannot proceed wait on condition variables declared inside the monitor.
Mutual exclusion is therefore automatic. Only the waiting logic is left to the programmer.
Java's synchronized methods with wait() and notify() follow this model. In C you build it by hand from a pthread_mutex_t and one or more pthread_cond_t variables, as shown below.
Condition variables
A condition variable is a queue of threads waiting for some condition about the monitor's data to become true. It supports three operations:
| Operation | Effect |
|---|---|
| `wait(c)` | Atomically releases the monitor lock and puts the caller to sleep on `c`. When woken, the thread must re-acquire the lock before continuing. |
| `signal(c)` | Wakes one thread waiting on `c`. If no thread is waiting, nothing happens. |
| `broadcast(c)` | Wakes all threads waiting on `c`. |
The "atomically releases and sleeps" step matters. If the release and the sleep were separate steps, a signal could arrive between them and the wakeup would be lost.
A condition variable holds no value. It is only a queue, and a condition variable is not a semaphore.
Semaphore versus condition variable
| Aspect | Semaphore | Condition variable |
|---|---|---|
| Holds state | Yes, an integer counter | No, only a queue of waiters |
| `signal` with no waiter | Increments the counter, so the signal is remembered | Lost, with no effect |
| `wait` | Blocks only if the counter is 0 | Always blocks |
| Used with a lock | Independent of any lock | Always used together with the monitor lock |
| Wakeup | Waiter proceeds directly | Waiter must re-acquire the lock first |
A classic GATE trap follows from the second row. If a thread signals a condition variable before the other thread has started waiting, the later wait sleeps forever. A semaphore would have remembered the signal.
Hoare versus Mesa semantics
When thread A signals and thread B wakes up, only one of them can be inside the monitor. Two designs resolve this.
- Hoare semantics (signal-and-wait). The signaller hands the monitor to the woken thread immediately and sleeps. The woken thread knows its condition is true, because nothing ran between the signal and its wakeup.
- Mesa semantics (signal-and-continue). The signaller keeps the monitor and continues. The woken thread is only made runnable and must compete for the lock later. Another thread may run first and make the condition false again.
Pthreads and Java use Mesa semantics. This leads to the most important rule in this chapter.
Bounded buffer as a monitor
This program is a complete producer-consumer solution. One mutex plays the role of the monitor lock, and two condition variables express "not full" and "not empty". The semaphore version needed three semaphores.
#include <pthread.h>
#include <stdio.h>
#define N 4
#define ITEMS 20
static int buf[N];
static int in = 0, out = 0, count = 0;
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
static pthread_cond_t not_full = PTHREAD_COND_INITIALIZER;
static pthread_cond_t not_empty = PTHREAD_COND_INITIALIZER;
static void put(int item) {
pthread_mutex_lock(&m);
while (count == N)
pthread_cond_wait(¬_full, &m);
buf[in] = item;
in = (in + 1) % N;
count++;
pthread_cond_signal(¬_empty);
pthread_mutex_unlock(&m);
}
static int get(void) {
pthread_mutex_lock(&m);
while (count == 0)
pthread_cond_wait(¬_empty, &m);
int item = buf[out];
out = (out + 1) % N;
count--;
pthread_cond_signal(¬_full);
pthread_mutex_unlock(&m);
return item;
}
static void *producer(void *arg) {
(void)arg;
for (int i = 0; i < ITEMS; i++)
put(i);
return NULL;
}
static void *consumer(void *arg) {
(void)arg;
long sum = 0;
for (int i = 0; i < ITEMS; i++)
sum += get();
printf("sum = %ld\n", sum);
return NULL;
}
int main(void) {
pthread_t p, c;
pthread_create(&p, NULL, producer, NULL);
pthread_create(&c, NULL, consumer, NULL);
pthread_join(p, NULL);
pthread_join(c, NULL);
return 0;
}Compile with gcc -pthread monitor.c -o monitor. The output is always sum = 190, the sum of 0 to 19.
Notice what is different from the semaphore version:
- The order of lock and wait is no longer a deadlock risk.
pthread_cond_waitreleases the mutex while sleeping, so a producer waiting on a full buffer never blocks the consumer. - The buffer state lives in
count, an ordinary variable, and thewhileconditions test it directly. - Each thread signals the opposite condition after it changes the state.
Common errors
- Using
ifinstead ofwhile. A woken consumer may find the buffer already emptied by another consumer, then remove an item that is not there. - Waiting without holding the lock.
pthread_cond_waitrequires the caller to hold the mutex. Without it, the check and the sleep are not atomic, and wakeups can be lost. - Signalling the wrong condition. If
putsignalsnot_fullinstead ofnot_empty, sleeping consumers are never woken. - Using
signalwhen several waiters need to run. If waiters wait for different conditions on one shared condition variable,signalmay wake the wrong one. Usebroadcast, or separate condition variables. - Calling a second monitor while holding the first. A thread that waits inside the inner monitor keeps the outer lock. This nested monitor call is a deadlock source.
Exam-style reasoning
Questions often ask whether a monitor program is correct under Hoare semantics but wrong under Mesa semantics. The usual pattern is an if guarding a wait. Under Hoare semantics, the woken thread runs at once, so the condition is guaranteed. Under Mesa semantics, a third thread can slip in between the signal and the wakeup. Trace this interleaving explicitly:
- Consumer C1 waits on an empty buffer.
- The producer inserts an item and signals, but keeps running and releases the lock.
- Consumer C2 arrives and takes the lock before C1 runs, and removes the item.
- C1 wakes with
count == 0. Withif, it reads an empty buffer. Withwhile, it goes back to sleep.
Exercise
A monitor-based program has a thread that executes signal(c) when no thread is waiting on c. A second thread then executes wait(c). What happens, and how would the outcome differ if c were a semaphore with initial value 0?
Show answer
With a condition variable, the earlier signal had no effect and was lost, so the second thread blocks until another signal arrives, possibly forever. With a semaphore of initial value 0, the earlier signal would have raised the counter to 1, so the later wait would decrement it to 0 and continue without blocking.
Exercise
In the bounded-buffer monitor above, the consumer's while (count == 0) is replaced by if (count == 0). Give an interleaving with two consumers and one producer under Mesa semantics that makes get return invalid data.
Show answer
Consumers C1 and C2 and a producer P, buffer empty. C1 calls get, finds count == 0 and waits. P inserts one item (count becomes 1) and signals not_empty, which makes C1 runnable, then releases the lock. Before C1 re-acquires the lock, C2 calls get, sees count == 1, removes the item (count becomes 0) and leaves. C1 now obtains the lock and, because if does not re-test, continues past the wait. It reads from an empty buffer and decrements count to -1. With while, C1 would re-test, see count == 0 and wait again.