Monitors
A high-level abstraction that provides equivalent functionality to that of semaphores and that is easier to control
The monitor construct has been implemented in a number of programming languages and as a program library
A programmer does not need to manually write the entire synchronization code
Monitors
monitor monitor-name { // shared variables declarations procedure P1 () { . } procedure Pn () {} Initialization code (.) { } }
Monitor
Protect shared objects within an abstraction
Provide encapsulation Accesses to a shared object is confined within a monitor
wait for buffer to A condition queuebecome full/empty The wait and signal functions
monitor
x
y
condition variable
function deposit (item) { if (counter = n) then full.wait; buffer[in] := item; in := (in+1) % n; counter := counter + 1; empty.signal; }
function remove (&item) { if (counter = 0) then empty.wait; item := buffer[out]; out := (out+1) % n; counter := counter 1; full.signal; }
monitor full
empty
counter := counter + 1; empty.signal; } function remove (&item) { if (counter = 0) then empty.wait; item := buffer[out];
out := (out+1) % n;
monitor full
empty
monitor full
empty
counter := counter + 1; empty.signal; } function remove (&item) { if (counter = 0) then empty.wait; item := buffer[out];
out := (out+1) % n;
function deposit (item) { while (counter = n) then full.wait; buffer[in] := item; in := (in+1) % n; counter := counter + 1; empty.notify; }
function remove (&item) { while (counter = 0) then empty.wait; item := buffer[out]; out := (out+1) % n; counter := counter 1; full. notify; }
monitor full
empty
watchdog timer
counter := counter + 1; empty.notify; } function remove (&item) { while (counter = 0) then empty.wait; item := buffer[out];
out := (out+1) % n;
Monitor
Monitor provides encapsulation
Accesses to a shared object is confined within a monitor Easier to debug the code
E.g., bounded buffer problem, deposit & remove functions