Monitors_in_Operating Systems Unit-3.pptx

ssuser09d6cd1 1 views 9 slides Oct 16, 2025
Slide 1
Slide 1 of 9
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9

About This Presentation

Monitors and its operation in operating systems


Slide Content

Monitors in Operating Systems Synchronization Mechanism with Dining Philosophers Example

What are Monitors? - Monitors are high-level synchronization constructs that encapsulate shared resources. - They provide mutual exclusion and condition variables for process synchronization. - Ensures that only one process can execute a monitor procedure at a time.

Monitor Syntax ```c monitor MonitorName { // Shared variables condition cond_var; function procedure1() { // Critical section } function procedure2() { // Another critical section } }

Dining Philosophers Problem - Problem: Five philosophers sit at a circular table with a fork between each pair. - They alternate between thinking and eating, needing both left and right forks to eat. - Solution: A monitor manages fork access using condition variables.

Dining Philosophers Implementation in C (Using Monitors) See next slide for the C code example.

C Code for Dining Philosophers (Part 1) ```c #include <stdio.h> #include <pthread.h> #define N 5 typedef enum { THINKING, HUNGRY, EATING } State; State state[N]; pthread_mutex_t mutex; pthread_cond_t condition[N]; void test(int i) { if (state[i] == HUNGRY && state[(i + 4) % N] != EATING && state[(i + 1) % N] != EATING) { state[i] = EATING; pthread_cond_signal(&condition[i]); } }

C Code for Dining Philosophers (Part 2) ```c void take_forks(int i) { pthread_mutex_lock(&mutex); state[i] = HUNGRY; test(i); if (state[i] != EATING) pthread_cond_wait(&condition[i], &mutex); pthread_mutex_unlock(&mutex); } void put_forks(int i) { pthread_mutex_lock(&mutex); state[i] = THINKING; test((i + 4) % N); test((i + 1) % N); pthread_mutex_unlock(&mutex); }

C Code for Dining Philosophers (Part 3) ```c void* philosopher(void* num) { int i = *(int*)num; while (1) { take_forks(i); put_forks(i); } } int main() { pthread_t philosophers[N]; int id[N]; pthread_mutex_init(&mutex, NULL); for (int i = 0; i < N; i++) { pthread_cond_init(&condition[i], NULL); id[i] = i; pthread_create(&philosophers[i], NULL, philosopher, &id[i]); } for (int i = 0; i < N; i++) pthread_join(philosophers[i], NULL); return 0; }

Advantages of Monitors - Encapsulation: Synchronization is hidden inside the monitor. - Automatic Mutual Exclusion: No explicit locks needed inside monitor functions. - Condition Variables: Allow processes to wait inside the monitor.
Tags