OS-Unit-II(Part-II)
OS-Unit-II(Part-II)
Process Synchronization is the task phenomenon of coordinating the execution of processes in such a way that no
two processes can have access to the same shared data and resources.
Process Synchronization is mainly when multiple processes are running together, and more than one processes try
to gain access to the same shared resource or any data at the same time.
Race Conditions
• Several processes access and manipulate the same data concurrently
• The outcome of the execution depends on the particular
order in which the access takes place is called Race Condition
• Prevent race condition by Synchronization
1. Ensure only one process at a time manipulates the critical data
EXAMPLE
Critical Section
1. When more than one processes access a same code segment that segment is known as critical section.
2. Critical section contains shared variables or resources which are needed to be synchronized to maintain
consistency of data variable.
3. In simple terms a critical section is group of instructions/statements or region of code that need to be
executed atomically, such as accessing a resource (file, input or output port, global data, etc.).
1. Each process must request permission to enter its critical section.
2. The section of code implementing this request
is the entry section.
3. The critical section may be followed
by an exit section.
4. The remaining code is the remainder section.
1
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
A solution to the critical-section problem must satisfy the following three requirements:
1. Mutual exclusion. If process Pi is executing in its critical section, then no other processes
can be executing in their critical sections.
2. Progress. When no process is the critical section, any process that requests entry into
the critical section must be permitted without any delay
3. Bounded waiting. There exists a bound, or limit, on the number of times that other
processes are allowed to enter their critical sections after a process has made a
request to enter its critical section and before that request is granted.
Here process A enters its critical region at time T1. A little later, at
time T2 process B attempts to enter its critical region but fails because
another process is already in its critical region and we allow only one
at a time.
Consequently, B is temporarily suspended until time T3 when A leaves
its critical region, allowing B to enter immediately. Eventually B leaves
(at T 4 ) and we are back to the original situation with no processes in
their critical regions.
2
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
1. As a second attempt, let us look for a software solution.
2. Lock variable is a synchronization mechanism.
3. It uses a lock variable to provide the synchronization among the processes executing concurrently.
4. However, it completely fails to provide the synchronization.
5. Multiprocessor solution
6. Executes in users mode
7. It is implemented as-
8. Initially, lock value is set to 0.
9. Lock value = 0 means the critical section is currently vacant and no process is present inside it.
10. Lock value = 1 means the critical section is currently occupied and a process is present inside it.
Working-
Scene-01:
1. Process P0 arrives.
2. It executes the lock!=0 instruction.
3. Since lock value is set to 0, so it returns value 0 to the while loop.
4. The while loop condition breaks.
5. It sets the lock value to 1 and enters the critical section.
6. Now, even if process P0 gets preempted in the middle, no other process can enter the critical section.
7. Any other process can enter only after process P0 completes and sets the lock value to 0.
Scene-02:
1. Another process P1 arrives.
2. It executes the lock!=0 instruction.
3. Since lock value is set to 1, so it returns value 1 to the while loop.
4. The returned value 1 does not break the while loop condition.
5. The process P1 is trapped inside an infinite while loop.
6. The while loop keeps the process P1 busy until the lock value becomes 0 and its condition breaks.
Scene-03:
1. Process P0 comes out of the critical section and sets the lock value to 0.
2. The while loop condition of process P1 breaks.
3. It sets the lock value to 1 and enters the critical section.
4. Now, even if process P1 gets preempted in the middle, no other process can enter the critical section.
5. Any other process can enter only after process P1 completes and sets the lock value to 0.
Failure of the Mechanism-
1. The mechanism completely fails to provide the synchronization among the processes.
2. It can not even guarantee to meet the basic criterion of mutual exclusion.
3
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
Explanation-
The occurrence of the following scenes may lead to two processes present inside the critical section at the same time-
Scene-01:
Process P0 arrives.
1. It executes the lock!=0 instruction.
2. Since lock value is set to 0, so it returns value 0 to the while loop.
3. The while loop condition breaks.
4. Now, process P0 gets preempted before it sets the lock value to 1.
Scene-02:
Another process P1 arrives.
1. It executes the lock!=0 instruction.
2. Since lock value is still 0, so it returns value 0 to the while loop.
3. The while loop condition breaks.
4. It sets the lock value to 1 and enters the critical section.
5. Now, process P1 gets preempted in the middle of the critical section.
Scene-03:
Process P0 gets scheduled again.
1. It resumes its execution.
2. Before preemption, it had already failed the while loop condition.
3. Now, it begins execution from the next instruction.
4. It sets the lock value to 1 (which is already 1) and enters the critical section.
Thus, both the processes get to present inside the critical section at the same time.
Problem of Proposal -2: Lock Variables
Suppose that one process reads the lock and sees that it is 0. Before it can set the lock to 1, another process is
scheduled, runs, and sets the lock to 1. When the first process runs again, it will also set the lock to 1, and two
processes will be in their critical regions at the same time.
Now you might think that we could get around this problem by first reading out the lock value, then checking it again
just before storing into it, but that really does not help.
1. The race now occurs if the second process modifies the lock just after the first process has finished its second check.
2. No Mutual Exclusion
4
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
4. This is because if one process does not enter the critical section, then other process will never get a chance to
execute again.
It is implemented as-
Initially, two processes Pi and Pj are available and want to execute into critical section.
The turn variable is equal to i hence Pi will get the chance to enter into the critical section. The value of Pi remains I
until Pi finishes critical section.
Pi finishes its critical section and assigns j to turn variable. Pj will get the chance to enter into the critical section. The
value of turn remains j until Pj finishes its critical section.
Working-
This synchronization mechanism works as explained in the following scenes-
Scene-01:
1. Process P0 arrives.
2. It executes the turn!=0 instruction.
3. Since turn value is set to 0, so it returns value 0 to the while loop.
4. The while loop condition breaks.
5. Process P0 enters the critical section and executes.
6. Now, even if process P0 gets preempted in the middle, process P1 can not enter the critical section.
7. Process P1 can not enter unless process P0 completes and sets the turn value to 1.
Scene-02:
1. Process P1 arrives.
1. It executes the turn!=1 instruction.
2. Since turn value is set to 0, so it returns value 1 to the while loop.
3. The returned value 1 does not break the while loop condition.
4. The process P1 is trapped inside an infinite while loop.
5. The while loop keeps the process P1 busy until the turn value becomes 1 and its condition breaks.
Scene-03:
1. Process P0 comes out of the critical section and sets the turn value to 1.
5
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
2. The while loop condition of process P1 breaks.
3. Now, the process P1 waiting for the critical section enters the critical section and execute.
4. Now, even if process P1 gets preempted in the middle, process P0 cannot enter the critical section.
5. Process P0 cannot enter unless process P1 completes and sets the turn value to 0.
Problem of Proposal -3: Turn Variable or Strict Alternation Approach
Characteristics-
1. The characteristics of this synchronization mechanism are-
2. It ensures mutual exclusion.
3. It follows the strict alternation approach.
4. It does not guarantee progress since it follows strict alternation approach.
5. It ensures bounded waiting since processes are executed turn wise one by one and each process is guaranteed
to get a chance.
6. It ensures processes does not starve for the CPU.
7. It is architectural neutral since it does not require any support from the operating system.
8. It is deadlock free.
9. It is a busy waiting solution which keeps the CPU busy when the process is actually waiting.
Peterson's Solution
1. Peterson's Solution is a classic software-based solution to the critical section problem. It is unfortunately not
guaranteed to work on modern hardware, due to vagaries of load and store operations.
2. Peterson's solution is based on two processes
3. Suppose system contains more than two process then peterson’s solution not sufficient
4. Peterson's solution requires two shared data items:
int turn - Indicates whose turn it is to enter into the critical section. If turn = = i, then process i is allowed into their
critical section.
boolean flag[ 2 ] - Indicates when a process wants to enter into their critical section. When process i wants to enter
their critical section, it sets flag[ i ] to true.
6
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
Proof: Mutual Exclusion
Bounded-Waiting
Case III: (Starvation)
P1 is executing its CS repeatedly
-upon exiting its CS, P1 sets flag [1] = false
-hence the while loop is false for P0 and it can go (sufficient?)
However, P1 may attempt to re-enter its CS before P0 has a chance to run.
- But to re-enter, P1 sets flag [1] to true and sets turn to 0
- Hence the while loop is true for P1 and it waits
- The while loop is now false for P0 and it can go
1. In the following diagram, the entry and exit sections are enclosed in boxes.
2. In the entry section, process i first raises a flag indicating a desire to enter the critical section.
3. Then turn is set to j to allow the other process to enter their critical section if process j so desires.
4. The while loop is a busy loop (notice the semicolon at the end), which makes process i wait as long as process j has
the turn and wants to enter the critical section.
7
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
5. Process i lowers the flag[ i ] in the exit section, allowing process j to continue if it has been waiting.
Note that the instruction "turn = j" is atomic, that is it is a single machine instruction which cannot be interrupted.
Synchronization Hardware
• In general we can provide any solution to critical section problem by using a simple tool called as LOCK where we
can prevent the race condition.
• Many systems provide hardware support (hardware instructions available on several systems) for critical section
code.
• In UniProcessor hardware environment by disabling interrupts we can solve the critical section problem. So that
Currently running code would execute without any preemption.
• But by disabling interrupts on multiprocessor systems is time taking so that it is inefficient
compared to UniProcessor system.
• Now a days Modern machines provide special atomic hardware instructions that allow us to either test memory
word and set value Or swap contents of two memory words automatically i.e. Done through an uninterruptible unit.
8
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
/* critical section */
lock = false;
/* remainder section */
} while (true );
boolean test and set(boolean *target)
{
boolean rv = *target;
*target = true;
return rv;
}
9
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
Mutual Exclusion with Sleep() and Wakeup()
1. when a processes wants to enter in its critical section , it checks to see if then entry is allowed.
2. If it is not, the process goes into tight loop and waits (i.e., start busy waiting) until it is allowed to enter. This approach
waste CPU-time.
3. Now look at some interprocess communication primitives is the pair of sleep-wakeup.
Sleep: It is a system call that causes the caller to block, that is, be suspended until some other process wakes it up.
Wakeup:It is a system call that wakes up the process. Both 'sleep' and 'wakeup' system calls have one parameter that
represents a memory address used to match up 'sleeps' and 'wakeups' .
The consumer wants to remove data the buffer but buffer is already empty.
Solution: Consumer goes to sleep until the producer puts some data in buffer and wakes consumer up.
Mutex Locks
1. The hardware solutions presented above are often difficult for
ordinary programmers to access, particularly on multi-processor
machines, and particularly because they are often platform-
dependent.
2. Therefore most systems offer a software API equivalent called mutex
locks or simply mutexes. ( For mutual exclusion )
3. The terminology when using mutexes is to acquire a lock prior to
entering a critical section, and to release it when exiting
1. Just as with hardware locks, the acquire step will block the process if the lock is in use
by another process, and both the acquire and release operations are atomic.
2. Acquire and release can be implemented as shown here
3. One problem with the implementation is the busy loop used to block processes in
the acquire phase. These types of locks are referred to as spinlocks, because the CPU just sits and spins while
blocking the process.
4. Spinlocks are wasteful of cpu cycles, and are a really bad idea on single-cpu single-threaded machines, because
the spinlock blocks the entire computer, and doesn't allow any other process to release the lock.
10
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
Semaphores
1. Semaphore a proposed by Edsgar Dijkstra is a technique to manage concurrent processes by using a simple inter
value, which is known as a semaphore.
2. A semaphore S is an integer variable which is non-negative and shared between threads. This variable is used to
solve the critical section problem and to achieve process synchronization in the multiprocessing
environment.
3. A semaphore S is an integer variable that, apart from initialization, is accessed only through two standard atomic
operations: wait() and signal().
1. The wait() termed P (from the Dutch proberen, which means “to test”);
2. signal() was originally called V (from verhogen, which means “to increment”).
Semaphore Usage
Types of Semaphores:
1. The value of a binary semaphore can range only between 0 and 1. In some systems the Binary Semaphore is
called as Mutex locks, because, as they are locks to provide the mutual exclusion
2. The value of a counting semaphore can range over an unrestricted domain. Counting semaphores can be used to
control access to a given resource consisting of a finite number of instances
3. The process that wish to use a resource must performs the wait() operation ( count is decremented )
4. The process that releases a resource must performs the signal() operation ( count is incremented )
5. When the count for the semaphore is 0 means that all the resources are being used by some processes.
Otherwise resources are available for the processes to allocate.
6. When a process is currently using a resource means that it blocks the resource until the count becomes > 0.
For example:
1. Let us assume that there are two processes p0 and p1 which consists of two statements s0 & s1 respectively.
2. Also assume that these two processes are running concurrently such that process p1 executes the statement s1
only after process p0 executes the statement s0.
11
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
wait (S){
S.value=S.value-1;
if (S.value < 0) {
add this process to waiting queue
block(); }
}
Implementation of signal: (definition of signal with no busy waiting)
Signal (S){
S.value=S.value +1;
if (value <= 0) {
remove a process P from the waiting queue
wakeup(P); }
}
Disadvantages of Semaphores
1. While a process is in its critical section, any other process that tries to enter its critical section must loop
continuously in the entry code.
2. Busy waiting wastes CPU cycles that some other process might be able to use productivity
3. This type of semaphore is also called spinlock because the process “spins“ waiting for the lock.
4. To overcome the need for busy waiting, we can modify the definition of the wait () and signal () semaphore
operations.
5. When a process executes the wait () operation and finds that the semaphore value is not positive, it must
wait.
6. How rather than engaging in busy waiting, the process can block itself.
7. The block operation places a process into a waiting queue associated with the semaphore, and the state of
the process is switched to the waiting state.
8. The control is transferred to the CPU scheduler, which selects another process to execute.
Deadlocks and Starvation
The implementation of semaphore with waiting queue may result in the situation where
two or more processes are waiting for an event is called as Deadlocked.
• To illustrate this, let us assume two processes P0 and P1 each accessing two semaphores
S and Q which are initialized to 1 :-
1. Now process P0 executes wait(S) and P1 executes wait(Q), assume that P0 wants
to execute wait(Q) and P1 executes wait(S). But it is possible only after process P1
executes the signal(Q) and P0 executes signal(S).
2. Starvation or indefinite blocking. A process may never be removed from the semaphore queue in which it is
suspended.
12
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
1. The bounded-buffer problem (Producer Consumer Problem) is one of the
classic problem of synchronization. Producer
2. There is a buffer of n slots and each slot is cable of storing one unit of Consumer
data..
3. There are two processes running namely Producer and Consumer, which
are operating on the buffer.
4. The producer tries to insert data into an empty slot of the buffer.
5. The consumer tries to remove data from a filled slot in the buffer. Buffer of n slots
1. The producer must not insert data when the buffer s full
2. The consumer must not remove data when the buffer is
empty
6. The Producer and Consumer should not insert and remove data simultaneously.
We will make use of three semaphores:
1. m(mutex), a binary semaphore which is used to acquire and release the lock.
2. empty, a counting semaphore whose initial value is the number of slots in the buffer since initially all slots are
empty.
3. Full ,counting semaphore whose initial value is 0.
Readers-Writers Problem
1. A database is to be shared among several concurrent processes.
2. Some of these processes may want only to read the database, whereas others may want to update (that is, to
read and write) the database.
13
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
3. We distinguish between these two types of processes by referring to the former as readers and to the latter as
writers.
4. if two readers access the shared data simultaneously, no adverse effects will result.
5. if a writer and some other process (either a reader or a writer) access the database simultaneously, chaos may
ensue.
6. To ensure that these difficulties do not arise, we require that the writers have exclusive access to the shared
database while writing to the database.
7. This synchronization problem is referred to as the readers–writers problem.
8. We will make use of two semaphores and an integer variable:
9. 1.mutex, a semaphore (initialized to 1) which is used to ensure mutual exclusion when readcount is upadated
i.e., when any reader enters or exit from the critical section.
10. 2.Wrt , a semphore (initialized to 1) common to both reader and writer processes.
11. 3.readcount , an integer variable (initialized to 0) that keeps tracks of how many processes are currently
reading the object.
12. The structure of a writer process.
do {
wait(mutex);
...
/* writing is performed */
...
signal(mutex);
} while (true);
wait (mutex) ;
readcount - - ; //a reader wants to leave
if (readcount == 0) // no reader is left in the critical section
signal (wrt) ; //writers can enter
signal (mutex) ; //reader leave
}
Dining-Philosophers Problem
1. Consider five philosophers who spend their lives thinking and eating.
2. When a philosopher thinks, she does not interact with her colleagues.
3. Philosopher gets hungry and tries to pick up the two chopsticks that are closest
to her left and right neighbors
4. A philosopher may pick up only one chopstick at a time.
5. Obviously, she cannot pick up a chopstick that is already in the hand of a
neighbour.
6. When a hungry philosopher has both her chopsticks at the
The situation of the dining philosophers.
same time, she eats without releasing the chopsticks.
14
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
7. When she is finished eating, she puts down both chopsticks and starts thinking again
8. One simple solution is to represent each chopstick with a semaphore.
9. A philosopher tries to grab a chopstick by executing a wait() operation on that semaphore.
10. She releases her chopsticks by executing the signal() operation on the appropriate semaphores.
11. Thus, the shared data are semaphore chopstick[5];
• Allow a philosopher to pick up her chopsticks only if both chopsticks are available (to do this, she must pick them
up in a critical section).
• Use an asymmetric solution—that is, an odd-numbered philosopher picks up first her left chopstick and then her
right chopstick, whereas an even numbered philosopher picks up her right chopstick and then her left chopstick.
Monitors
A high-level abstraction that provides a convenient and effective mechanism for process synchronization.
• A procedure can access only those variables that are declared in a monitor and formal parameters
• Only one process may be active within the monitor at a time
15
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM
Syntax of the monitor :-
monitor monitor-name
{
// shared variable declarations
procedure P1 (…) { …. }
…
Schematic view of a Monitor
procedure Pn (…) {……}
Initialization code ( ….) { … }
…
}
Dining-Philosophers Solution Using Monitors
1. This solution to the dining philosophers uses monitors, and the restriction that a philosopher may only pick
up chopsticks when both are available. There are also two key data structures in use in this solution:
2. enum { THINKING, HUNGRY,EATING } state[ 5 ];
3. A philosopher may only set their state to eating when neither of their adjacent neighbors is eating.
1. ( state[ ( i + 1 ) % 5 ] != EATING && state[ ( i + 4 ) % 5 ] != EATING ).
4. condition self[ 5 ]; This condition is used to delay a hungry philosopher who is unable to acquire chopsticks.
5. In the following solution philosophers share a monitor, DiningPhilosophers, and eat using the following
sequence of operations:
6. DiningPhilosophers.pickup( ) - Acquires chopsticks, which may block the process. eat
7. DiningPhilosophers.putdown( ) - Releases the chopsticks.
16
UNIT-2 OPERATING SYSTEMS, DEPT.OF CSE, ACOE, SURAMPALEM