Table of Contents

Monitor

Monitor is a synchronization primitive combining a mutex with condition variables, allowing a thread to wait for a condition while holding a lock and be woken by another thread. This structured pattern avoids deadlocks compared to separate mutexes and semaphores.

Monitors are the basis for concurrent data structures like queues where producers signal waiting consumers.

Example

This example shows a monitor-like pattern with mutex and condition variable.

// compile: gcc -pthread -o monitor monitor.c
// run: ./monitor
// description: condition variable for signaling between threads
 
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
 
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int ready = 0;
 
void* waiter(void* arg) {
    pthread_mutex_lock(&lock);
    while (!ready) {
        pthread_cond_wait(&cond, &lock);
    }
    printf("Waiter woken\n");
    pthread_mutex_unlock(&lock);
    return NULL;
}
 
void* signaler(void* arg) {
    sleep(1);
    pthread_mutex_lock(&lock);
    ready = 1;
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&lock);
    return NULL;
}
 
int main() {
    pthread_t w, s;
    pthread_create(&w, NULL, waiter, NULL);
    pthread_create(&s, NULL, signaler, NULL);
    pthread_join(w, NULL);
    pthread_join(s, NULL);
    return 0;
}