CS6502 Operating Systems - Dr. J. Garrido Synchronization – Part 2 (Lecture 6) CS5002 Operating Systems Dr. Jose M. Garrido
Jan 12, 2016
CS6502 Operating Systems - Dr. J. Garrido
Synchronization – Part 2
(Lecture 6)
CS5002 Operating SystemsDr. Jose M. Garrido
CS6502 Operating Systems - Dr. J. Garrido
Classical Synchronization Problems
1. Bounded-buffer problem – also called the producer/consumer problem
2. Readers-writers problem
3. Dining philosophers
CS6502 Operating Systems - Dr. J. Garrido
Producer Consumer Problem
• Producer process generates data items • Consumer process takes these data items
and consumes them• Buffer - a container of N data items, filled
by the producer process and emptied by the consumer process
• Why is the buffer needed?
CS6502 Operating Systems - Dr. J. Garrido
Producer Consumer Problem (2)
• Competition between two processes to access the shared buffer
• Cooperation needed from the two processes in order to exchange data through the buffer
CS6502 Operating Systems - Dr. J. Garrido
Producer-Consumer Problem
CS6502 Operating Systems - Dr. J. Garrido
Synchronization Needed
• The buffer is necessary to allow the two processes to execute concurrently
• The producer and consumer processes must be synchronized to achieve:– Mutual exclusive access to the data
buffer– The producer must wait to place a new
data item if buffer is full– The consumer process must wait to
remove a data item if buffer is empty
CS6502 Operating Systems - Dr. J. Garrido
Semaphores in Solution
Three semaphores are needed:
• A binary semaphore for the mutual exclusive access to the data buffer
• A counting semaphore to count the number of full slots in the buffer
• A counting semaphore to count the number of empty slots in the buffer
CS6502 Operating Systems - Dr. J. Garrido
Data Declaration for the Solution
Shared data
int N = 100;
char buffer [N];
char nextp, nextc: item;
Semaphorec full, empty;
Semaphoreb mutex;
CS6502 Operating Systems - Dr. J. Garrido
Creating Semaphore Objects
full = new Semaphorec(0); // counting semaphore objempty = new Semaphorec( N); // counting sem objmutex = new Semaphoreb(1); // binary semaphore obj
CS6502 Operating Systems - Dr. J. Garrido
Body of Producer
Producer processwhile(true) {
…
produce an item in nextp
…
empty.wait(); // any empty slots? Decrease empty slots
mutex.wait(); // attempt exclusive access to buffer
// insert nextp into buffer
mutex.signal(); // release exclusive access to buffer
full.signal(); // increment full slots
}
CS6502 Operating Systems - Dr. J. Garrido
Body of Consumer
Consumer processwhile(true) {
full.wait(); // any full slots? Decrease full slots
mutex.wait(); // attempt exclusive access to buffer
…
// remove a data item from buffer to nextc
…
mutex.signal(); // release exclusive access to buffer
empty.signal(); // increment empty slots
…
// consume the data item in nextc
}
CS6502 Operating Systems - Dr. J. Garrido
Implementation of the Model
• The C++ implementation of the simulation model for the producer-consumer problem stored in file bbuffer3.cpp.
• The model has only three main classes: buffer, producer, and consumer.
• The last two classes that correspond (represent) active object types.
CS6502 Operating Systems - Dr. J. Garrido
Results of Simulation Run
• The only performance measure displayed is the total wait time for each process, for the simulation period given.
• Since the faster process always has to wait for the slower process, changing the mean periods to produce and to consume an item will have an effect on the performance measures.
CS6502 Operating Systems - Dr. J. Garrido
The Readers-Writers Problem
• There are two types of processes:– Readers– Writers
• There are several processes of each type.• These processes share a data resource, the
readers only access the data to read; the writers need access to the data resource to update the data.
CS6502 Operating Systems - Dr. J. Garrido
General Behavior of the Problem
The problem has the following restrictions:
• One or more reader processes can access the shared data simultaneously.
• When a writer process gains access to the shared data, the process has exclusive access to the shared resource to update the data.
CS6502 Operating Systems - Dr. J. Garrido
Simple Strategy for the Solution
• When a reader process arrives, it starts to read immediately if there is one or more reader processes already reading.
• If new reader processes continue to arrive, any writer process must wait.
• The first reader process that needs access to the shared data must compete with any writer process.
CS6502 Operating Systems - Dr. J. Garrido
Readers Access to Shared Data
• Writers need “individual” exclusive access to the shared data object
• Readers need “group” exclusive access to the shared data object– All the reader processes in a group are
able to access the shared data object – once the first reader has gained
exclusive access to the shared data object
CS6502 Operating Systems - Dr. J. Garrido
First and Last Readers
• Why are the first reader and last reader in a group important?
• The first reader competes with writers to gain exclusive group access to the shared data object
• The last reader releases exclusive group access to the shared data object; it gives a chance to the waiting writers
CS6502 Operating Systems - Dr. J. Garrido
Identifying First and Last Readers
• In the solution to this problem, a counter variable, readcount, is needed to keep a count of the number of reader processes that are accessing the shared data
• When readers request access to the shared data, the counter is incremented
• When readers complete access to the shared data, the counter is decremented
CS6502 Operating Systems - Dr. J. Garrido
The Counter Variable
• The counter variable, readcount, is used by readers only
• Every reader process has to increment this counter on requesting access to the shared data
• Every reader has to decrement this counter when access to the shared data is completed
• The use of this counter variable has to be done in a mutual exclusive manner by every reader
CS6502 Operating Systems - Dr. J. Garrido
Identifying First and Last Readers
• For the first reader, the counter is 1
• For the last reader, the counter is 0.
CS6502 Operating Systems - Dr. J. Garrido
Readers-Writers Solution
• Two binary semaphores are used• The mutex semaphore is used to ensure
mutual exclusion (among readers) when the variable readcount is updated.
• The semaphore wrt controls mutual exclusive access for writers.
• Semaphore wrt is also used by the first and last reader that enters or exits the critical section.
CS6502 Operating Systems - Dr. J. Garrido
Global Variables
integer readcount = 0; // used by readers only
Semaphoreb mutex, wrt;
mutex = new Semaphoreb (1);wrt = new Semaphore (1);
CS6502 Operating Systems - Dr. J. Garrido
Writer Process
Writer { . . .
wrt.wait (); // get access to the shared object
… write to shared data object (exclusive access)
wrt.signal (); . . . } // end of writer
CS6502 Operating Systems - Dr. J. Garrido
Reader Process
Reader { mutex.wait (); increment readcount; if reacount equals 1 then // first reader? wrt.wait (); // gain group access to shared data mutex.signal (); // Critical Section // read shared data object mutex.wait(); decrement readcount; if readcount equals zero then // last reader? wrt.signal (); // release group access to shared data mutex.signal ();} // end Reader
CS6502 Operating Systems - Dr. J. Garrido
Observations on R-W Problem
• If a writer is in the critical section and n readers are waiting, then one reader is queued on wrt and n-1 readers are queued on mutex.
• When a writer executes wrt.signal(), the OS resumes the execution of either:– waiting readers, or– a single waiting writer.
CS6502 Operating Systems - Dr. J. Garrido
Readers & Writers Problem Issues
• No reader will be kept waiting unless a writer has already obtained permission to access the shared data
• Once a writer is ready to access the shared data, the writer performs its operation as soon as possible (i.e., no new readers may start reading).
CS6502 Operating Systems - Dr. J. Garrido
Simulation Models of the Readers Writers
• The Java files are stored in the archive file readwrite.jar and the model with the GUI is stored in the archive file rwrite2.jar.
• The C++ version of this model is stored in file reawriter.cpp. The model implements the first strategy for solving the readers-writers problem.
• The simulation models of the readers-writers problem follow very closely the theoretical discussion.
CS6502 Operating Systems - Dr. J. Garrido
Partial Results of a Simulation Run
Project: Concurrent Readers/Writers ProblemRun at: Thu Mar 02 15:20:37 EST 2006 -----------------------------------------------------Input ParametersSimulation Period: 740Arrivals Stop: 400Reader Inter Arrival Time: 5.5Writer Inter Arrival Time: 7.5Mean Write Time: 17.5Mean Read Time: 12.75Writer Priority: 10Reader Priority: 10Results of simulation: Concurrent Readers/Writers Problem---------------------------------------------------------Results of simulation:Number of Readers that Arrived: 87Number of Readers that completed: 87Average reader wait period: 0164.1250Number of Writers that Arrived: 45Number of Writers that completed: 28Average writer wait period: 0234.5263
CS6502 Operating Systems - Dr. J. Garrido
Synchronization Using Monitors
• Monitors are higher-level mechanisms for the synchronization of interacting processes, compared with semaphores.
• Monitors are abstract data types. They take full advantage of the encapsulation principle provided by object-oriented programming languages.
• Only a single process can be executing an operation of the monitor at any given time.
CS6502 Operating Systems - Dr. J. Garrido
Monitors
• A monitor implements a mechanism that facilitates the use of mutual exclusion
• In addition to the entry queue for waiting processes that need to enter the monitor, there are one or more condition queues
• Each condition queue corresponds to a condition variable.
CS6502 Operating Systems - Dr. J. Garrido
Synchronization with Monitors
• In a similar manner to the use of semaphores, monitors are used to solve various synchronization problems.
• The main advantage of using monitors in solving synchronization problems is the higher-level construction.
• Brinch Hansen's approach for the semantics of monitor requires that a process that executes a signal operation must exit the monitor immediately.
• The signal statement must be the last one defined in the monitor function. Anthony Hoare proposed a slightly different semantics for monitors.
CS6502 Operating Systems - Dr. J. Garrido
Producer-Consumer with Monitors
• The simulation models of the producer-consumer problem with monitors also follow very closely the theoretical discussion. The Java implementation of the model includes the classes: Buffer, Condition, Consprod, Consumer, PCmonitor, Producer, and Semaphore.
• These Java files are stored in the archive file consprodm.jar.
• The C++ version of this model is stored in file consprodm.cpp. The model implements the first strategy for solving the readers-writers problem.
CS6502 Operating Systems - Dr. J. Garrido
• Illustrates processes that are competing for exclusive access to more than one resources, such as tape drives or I/O devices.
• A monastery’s dining table
– Circular
– Five plates
– Five forks (critical)
– Plate of noodles at center of table (endless supply)
– Philosophers can only reach forks adjacent to their plate (left and right forks)
Dining Philosophers
CS6502 Operating Systems - Dr. J. Garrido
Life of a Philosopher
1. Spends some time thinking
2. Gets hungry
3. Sits at the table,
4. Attempts to get the left fork
5. Attempts to get the right fork
6. Starts eating, this activity takes a finite time
7. Releases the left and right forks
8. Returns to the initial state (thinking)
CS6502 Operating Systems - Dr. J. Garrido
Dinning Table
CS6502 Operating Systems - Dr. J. Garrido
Dining-Philosophers Problem
// Shared data Semaphore fork[] = new Semaphore[5];
Every philosopher needs two forks and these must be accessed in a mutual exclusive manner
CS6502 Operating Systems - Dr. J. Garrido
Philosophers Body
Philosopher run() {
while (true) {
// get left fork
fork[i].wait();
// get right fork
fork[(i + 1) % 5].wait();
// eat for a finite time interval
// return left fork
fork[i].signal();
// return right fork
fork[(i + 1) % 5].signal();
// think for finite time interval
}
} // end run()
CS6502 Operating Systems - Dr. J. Garrido
•When a philosopher is hungry–obtains 2 forks (1 at a time)–Proceeds to eat
•When a philosopher has satisfied hunger returns both forks and goes back to think
•Problem: There are 5 competing philosopher processes
•Using semaphores as before, is not sufficient for solving the problem
Why Synchronize?
CS6502 Operating Systems - Dr. J. Garrido
•Suppose all philosophers want to eat at the same time
•Each one will pick up the left fork first then block trying to pickup the right fork
•All processes will now block indefinitely - deadlock
Dining Philosophers 1st Attempt
CS6502 Operating Systems - Dr. J. Garrido
Dinning Philosophers 2nd Attempt
• After taking the left fork, if the right fork is not available, philosopher puts back the left fork and waits for a while.
• Problem: Suppose all philosophers want to eat at the same time:– Each will pick up the left fork first and then
try to pick up the right fork.– The right fork is not available, so all
philosophers put back left forks and wait.– After some time, philosophers pick up the
left fork and try again - the cycle repeats.
CS6502 Operating Systems - Dr. J. Garrido
•Use a binary semaphore, mutex, to make eating mutually exclusive.
•A philosopher is guaranteed to get both forks in this case.
•Problem: Only one philosopher can be eating at any given time.
Dining Philosophers 3rd Attempt
CS6502 Operating Systems - Dr. J. Garrido
4th Attempt to a Solution
• A philosopher’s neighbors are defined by macros LEFT & RIGHT.
• A philosopher may move only into eating state if neither neighbor is eating.
• Use an array, state, to keep track of whether a philosopher is eating, thinking or hungry (trying to acquire forks).
• Use an array of semaphores, one per philosopher, so hungry philosophers can block if the needed forks are busy.