5.4.1 Concept of Monitors(2/10) .a Formal definition A monitor defines a lock and zero or more condition variables for managing concurrent access to shared data The monitor uses the lock to insure that only a single thread is active in the monitor at any instance The lock also provides mutual exclusion for shared data Condition variables enable threads to go to sleep inside of critical sections, by releasing their lock at the same time it puts the thread to sleep
5.4.1 Concept of Monitors(2/10) • A Formal Definition • A Monitor defines a lock and zero or more condition variables for managing concurrent access to shared data. • The monitor uses the lock to insure that only a single thread is active in the monitor at any instance. • The lock also provides mutual exclusion for shared data. • Condition variables enable threads to go to sleep inside of critical sections, by releasing their lock at the same time it puts the thread to sleep. 7
5.4.1 Concept of Monitors(3/10) · Monitor operations: Encapsulates the shared data you want to protect Acquires the mutex at the start Operates on the shared data Temporarily releases the mutex if it can't complete Reacquires the mutex when it can continue Releases the mutex at the end
5.4.1 Concept of Monitors(3/10) • Monitor operations: • Encapsulates the shared data you want to protect. • Acquires the mutex at the start. • Operates on the shared data. • Temporarily releases the mutex if it can't complete. • Reacquires the mutex when it can continue. • Releases the mutex at the end. 8
5.4.1 Concept of Monitors(4/10) Structure of a monitor queue entering processes monitor waiting area Entrance Lock MONITOR condition cl local data waitre I condition variables Procedure l Condition Variables condition er ewalt(cn) Procedure k 工兽 urgent queue initialization code Lxi量 re s.1s Structure of a Monitor
5.4.1 Concept of Monitors(4/10) • Structure of a Monitor 9 Lock Condition Variables
5.4.1 Concept of Monitors (5/10) Procedures are mutual exclusive Shared data Queue of waiting processes trying to enter the monitor procedures
5.4.1 Concept of Monitors(5/10) • Procedures are mutual exclusive 10
5.4.1 Concept of Monitors(6/10) It is simple to turn a java class into a monitor Make all the data private Make all methods synchronized or at least the non private ones) class Queuet private…;∥/ queue data public void synchronized Add( object item t put item on queue public object synchronized removed i if queue not empty i remove item return item
5.4.1 Concept of Monitors(6/10) • It is simple to turn a Java class into a monitor: • Make all the data private • Make all methods synchronized (or at least the non - private ones) 11 class Queue{ private ...; // queue data public void synchronized Add( Object item ) { put item on queue; } public Object synchronized Remove() { if queue not empty { remove item; return item; } }