Classical Problem of Synchronization
Classical Problem of Synchronization
Classical Problem of Synchronization
Producer-Consumer
with an unbounded
buffer Producer-Consumer with a bounded buffer Reader-Writer problem Dining Philosopher problem
Producer-Consumer with an unbounded buffer: A buffer of unbounded capacity is set aside to smooth the speed difference between producer and consumer. A producer must be the first process to run in order to provide the first item.
A consumer process may run whenever there is more than one item in the buffer produced but not yet consumed. Producer may run at any time without restriction.
Variable produced: semaphore; Process producer begin While true do begin produce
place_in_buffer
signal (produced) other _producer _ processing end (while) End (producer)
Process consumer begin While true do begin wait (produced) take _from _buffer consume other _consumer _ processing end (while) End (consumer)
Process consumer begin While true do begin wait (mayconsumed) wait(cmutex) citem := buffer [ out ] out :=out +1 signal (cmutex) signal (mayproduce) other _consumer_processing end (while) End (consumer)
Reader/Writer problem
Readcount:integer mutex,write:semaphore (binary) Process reader Begin While true do begin wait (mutex) readercount := readercount + 1; if readercount = 1 then wait(write) Signal(mutex) [read] Wait(mutex) readercount := readercount -1; if readercount =0 then signal(write) Signal(mutex) Other processing End{while}; end {reader}
Process writer
Begin While true do begin wait (write) .[writes] Signal(write) Other processing end {while}; end {writer}
Solution :do { wait (chopstick [i]); wait (chopstick [ ( i+1 ) % 5 ]); // eat signal (chopstick [i]); signal (chopstick [ ( i+1 ) % 5 ] );
//think
}while (true);
What is a monitor?
A collection of data and procedures High level of data abstraction tool that automatically generates atomic operations on a given data structure
A monitor has
Shared data A set of atomic operations on that data A set of condition variables
Why monitors?
Concurrency has always been an OS issue
Resource allocation is necessary among competing processes Timer interrupts
Existing synchronization mechanisms (semaphores, locks) are subject to hard-to-find Reduce probability of errors
Monitor Implementation
Each monitor has one lock. Acquire lock when begin a monitor operation, and release lock when operation finishes