- Semaphores are useful and powerful
- But, they require programmer to think of every timing issue; easy to miss something, difficult to debug
- Let the compiler handle the details
- Monitors are a high level language construct for dealing with synchronization
- similar to classes in Java
- a monitor has fields and methods
- A monitor is a software module implementing mutual exclusion
- Monitors are easier to program than semaphores
- programmer only has to say what to protect
- compiler actually does the protection (compiler will use semaphores to do protection)
- Natively supported by a number of programming languages: Java
- Resources or critical sections can be protected using the keyword: synchronized keyword
- synchronized can be applied to a method: entire method is a critical section
- Chief characteristics (see Fig. 2):
- Local data variables are accessible only by the monitor (not externally)
- Process enters monitor by invoking one of its procedures, but cannot directly access the monitor's internal datastructures
- Only one process may be executing in the monitor at a time (mutual exclusion)
- Only methods inside monitor can access fields
- At most one thread can be active inside monitor at any one time
- Main problem: provides less control
- Allow process to wait within the monitor with condition variable, condition x,y;
- can only be used with operations wait and
signal (notify() in Java);
- operation wait(x); means that the process invoking this operation is suspended until another process invokes signal(x);
- operation signal(x); resumes exactly one process suspended
- condition variables are not counters, they do not accumulate signals for later use the way the semaphores do. Thus if a condition variable is signaled with no waiting on it, the signal is lost
- This solution is deadlock free
- In Fig. 3, the solution for the producer-consumer problem with a monitor is given
- The class our_monitor contains the buffer, the administration variables and two synchronized methods
- when the producer is active in insert, it knows for sure that the consumer can not be active inside remove
- making it safe to update the variables and buffer without fear of race conditions
Figure 3:
The producer-consumer problem with a monitor.
|
2004-04-03