Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

Chapter 5: Process

Synchronization

Operating System Concepts – 9th Edition Silberschatz, Galvin and Gagne ©2013
Chapter 6: Process Synchronization
Background
The Critical-Section Problem
Peterson’s Solution
Synchronization Hardware
Mutex Locks
Semaphores
Classic Problems of Synchronization
Monitors
Synchronization Examples
Alternative Approaches

Operating System Concepts – 9th Edition 5.2 Silberschatz, Galvin and Gagne ©2013
Objectives

To present the concept of process synchronization.


To introduce the critical-section problem, whose solutions can be used
to ensure the consistency of shared data
To present both software and hardware solutions to the critical-section
problem
To examine several classical process-synchronization problems.
To explore several tools that are used to solve process synchronization
problems

Operating System Concepts – 9th Edition 5.3 Silberschatz, Galvin and Gagne ©2013
Cooperating Processes
Independent process cannot affect or be affected by the execution of
another process
Cooperating processes can affect or be affected by the execution of
another process.
They can share:
 Variable
 Memory
 Code
 Resources (CPU, Printer, Scanner).

Operating System Concepts – 9th Edition 5.4 Silberschatz, Galvin and Gagne ©2013
Background
Processes can execute concurrently
May be interrupted at any time, partially completing execution
Concurrent access to shared data may result in data inconsistency.
Maintaining data consistency requires mechanisms to ensure the
orderly execution of cooperating processes.
Illustration of the problem:

Operating System Concepts – 9th Edition 5.5 Silberschatz, Galvin and Gagne ©2013
Producer-Consumer Problem
Paradigm for cooperating processes, producer process produces
information that is consumed by a consumer process
unbounded-buffer places no practical limit on the size of the buffer
bounded-buffer assumes that there is a fixed buffer size

Operating System Concepts – 9th Edition 5.6 Silberschatz, Galvin and Gagne ©2013
Producer-Consumer Problem

Operating System Concepts – 9th Edition 5.7 Silberschatz, Galvin and Gagne ©2013
Bank Problem

The following race condition occurs:


1.App A reads the current balance, which is ₹1000
2.App A adds ₹200 to ₹1000 and gets ₹1200 as the final balance
3.Meanwhile, app B fetches the current balance, which is still ₹1000, as app A has
not executed step 3
4.App B adds ₹500 to ₹1000 and gets ₹1500 as the final balance
5.App B updates the account balance to ₹1500
6.App A updates the account balance to ₹1200
Thus the final balance is ₹1200 instead of ₹1700

Operating System Concepts – 9th Edition 5.8 Silberschatz, Galvin and Gagne ©2013
Printer-Spooler Problem

Operating System Concepts – 9th Edition 5.9 Silberschatz, Galvin and Gagne ©2013
Race Condition

counter++ could be implemented as


register1 = counter
register1 = register1 + 1
counter = register1
counter-- could be implemented as
register2 = counter
register2 = register2 - 1
counter = register2

Consider this execution interleaving with “count = 5” initially:


S0: producer execute register1 = counter {register1 = 5}
S1: producer execute register1 = register1 + 1 {register1 = 6}
S2: consumer execute register2 = counter {register2 = 5}
S3: consumer execute register2 = register2 – 1 {register2 = 4}
S4: producer execute counter = register1 {counter = 6 }
S5: consumer execute counter = register2 {counter = 4}

Operating System Concepts – 9th Edition 5.10 Silberschatz, Galvin and Gagne ©2013
Race Condition
A Race condition is a scenario that occurs in a multithreaded /
multiprogramming environment due to multiple threads/processes
sharing the same resource or executing the same piece of code. If not
handled properly, this can lead to an undesirable situation, where the
output state is dependent on the order of execution of the
threads/process.

Operating System Concepts – 9th Edition 5.11 Silberschatz, Galvin and Gagne ©2013
Critical Section Problem
Consider system of n processes {p0, p1, … pn-1}
Each process has critical section segment of code
Process may be changing common variables, updating table, writing
file, etc
When one process in critical section, no other may be in its critical
section
Critical section problem is to design a protocol to solve this
Each process must ask permission to enter critical section in entry
section code, once it finishes executing in the critical section, it enters the
exit section code, then the process enters the remainder section code.

Operating System Concepts – 9th Edition 5.12 Silberschatz, Galvin and Gagne ©2013
Critical Section

General structure of process Pi

Operating System Concepts – 9th Edition 5.13 Silberschatz, Galvin and Gagne ©2013
Solution to Critical-Section Problem
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 - If no process is executing in its critical section and there exist
some processes that wish to enter their critical section, then the selection
of the processes that will enter the critical section next cannot be
postponed indefinitely
3. Bounded Waiting - A bound must exist 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
 Assume that each process executes at a nonzero speed
 No assumption concerning the relative speed of the n processes

Operating System Concepts – 9th Edition 5.14 Silberschatz, Galvin and Gagne ©2013
Critical-Section Handling in OS
Two approaches depend on if the kernel is preemptive or non-
preemptive
Preemptive – allows preemption of the process when running in
kernel mode
Non-preemptive – runs until exits kernel mode, blocks, or
voluntarily yields CPU
Essentially free of race conditions in kernel mode

Operating System Concepts – 9th Edition 5.15 Silberschatz, Galvin and Gagne ©2013
Solution to Critical-section Problem Using Locks

Operating System Concepts – 9th Edition 5.16 Silberschatz, Galvin and Gagne ©2013
Two Process Solution (Using turn variable)
• Turn Variable or Strict Alternation Approach is the software mechanism
implemented in user mode.
• It is a busy waiting solution that can be implemented only for two
processes.
• In this approach, A turn variable is used which is actually a lock.

Operating System Concepts – 9th Edition 5.17 Silberschatz, Galvin and Gagne ©2013
Two Process Solution (Using turn variable)

Operating System Concepts – 9th Edition 5.18 Silberschatz, Galvin and Gagne ©2013
Two Process Solution (Using flag)

Process P(i) Process P(j)


While(True) While(True)
{ {
flag[i] = T; flag[j] = T;
while(flag[j]); while(flag[i]);
Critical Section Critical Section
flag[i] = F flag[j] = F
} }

Operating System Concepts – 9th Edition 5.19 Silberschatz, Galvin and Gagne ©2013
Peterson’s Solution
Good algorithmic description of solving the problem
Two process solution
Assume that the load and store machine-language instructions
are atomic; that is, cannot be interrupted
The two processes share two variables:
int turn;
Boolean flag[2]

The variable turn indicates whose turn it is to enter the critical section
The flag array is used to indicate if a process is ready to enter the
critical section. flag[i] = true implies that process Pi is ready!

Operating System Concepts – 9th Edition 5.20 Silberschatz, Galvin and Gagne ©2013
Algorithm for Process Pi and Pj

Operating System Concepts – 9th Edition 5.21 Silberschatz, Galvin and Gagne ©2013
Peterson’s Solution (Cont.)
Provable that the three CS requirements are met:
1. Mutual exclusion is preserved
Pi enters CS only if:
either flag[j] = false or turn = i
2. Progress requirement is satisfied
3. Bounded-waiting requirement is met

Operating System Concepts – 9th Edition 5.22 Silberschatz, Galvin and Gagne ©2013
Synchronization Hardware
Process Synchronization problems occur when two processes
running concurrently share the same data or the same variable.
The value of that variable may not be updated correctly before its
being used by a second process. Such a condition is known as Race
Around Condition.
There are software as well as hardware solutions to this problem.
Hardware Methods:
1. Test and Set
2. Swap

Operating System Concepts – 9th Edition 5.23 Silberschatz, Galvin and Gagne ©2013
Solution using test_and_set()

while (test_and_set(&lock));
critical section
lock = false;

boolean test_and_set (boolean *target)


{
boolean rv = *target;
*target = TRUE;
return rv:
}

Operating System Concepts – 9th Edition 5.24 Silberschatz, Galvin and Gagne ©2013
Solution using test_and_set()

TestAndSet(lock) algorithm works in this way – it always returns


whatever value is sent to it and sets lock to true.
The first process will enter the critical section at once as
TestAndSet(lock) will return false and it’ll break out of the while loop. The
other processes cannot enter now as the lock is set to true and so the
while loop continues to be true. Mutual exclusion is ensured.
Once the first process gets out of the critical section, the lock is changed
to false. So, now the other processes can enter one by one. Progress is
also ensured.
However, after the first process, any process can go in. There is no
queue maintained, so any new process that finds the lock to be false
again can enter. So bounded waiting is not ensured.

Operating System Concepts – 9th Edition 5.25 Silberschatz, Galvin and Gagne ©2013
Swap algorithm
• Swap algorithm is a lot like the
TestAndSet algorithm.

• Instead of directly setting the


lock to true in the swap function,
the key is set to true and then
swapped with the lock.

• First process will be executed,


and in while(key), since
key=true, swap will take place
and hence lock=true and
key=false.

• Again next iteration takes place


while(key) but key=false, so
while loop breaks, and the first
process will enter in the critical
section.

Operating System Concepts – 9th Edition 5.26 Silberschatz, Galvin and Gagne ©2013
Swap algorithm
Now another process will try to enter in
the Critical section, so again key=true
and hence while(key) loop will run and
swap takes place so, lock=true and
key=true (since lock=true in first
process).
Again on next iteration while(key) is
true so this will keep on executing and
another process will not be able to
enter in critical section. Therefore
Mutual exclusion is ensured.
Again, out of the critical section, lock is
changed to false, so any process
finding it gets t enter the critical section.
Progress is ensured.
However, again bounded waiting is not
ensured for the very same reason.

Operating System Concepts – 9th Edition 5.27 Silberschatz, Galvin and Gagne ©2013
Bounded-waiting Mutual Exclusion with test_and_set

Operating System Concepts – 9th Edition 5.28 Silberschatz, Galvin and Gagne ©2013
Semaphore
Semaphore is an Integer Variable that is used in mutual exclusion manner by
various concurrent processes in order to achieve synchronization.
Semaphore S – Integer Variable
Can only be accessed via two indivisible (atomic) operations.
wait() and signal()
 Originally called P() and V()

Definition of the wait() operation


wait(S) {
while (S <= 0); // busy-wait
S--;
}
Definition of the signal() operation
signal(S) {
S++;
}

Operating System Concepts – 9th Edition 5.29 Silberschatz, Galvin and Gagne ©2013
Semaphore Usage
Counting semaphore – integer value can range over an unrestricted domain
Binary semaphore – integer value can range only between 0 and 1
Same as a mutex lock
Can solve various synchronization problems
Consider P1 and P2 that require S1 to happen before S2
Create a semaphore “synch” initialized to 0
P1:
S1;
signal(synch);
P2:
wait(synch);
S2;

Operating System Concepts – 9th Edition 5.30 Silberschatz, Galvin and Gagne ©2013
Semaphore for Critical Section Problem
Definition of the wait(S) operation
wait(S) {
while (S <= 0); // busy-wait
S--;
}
Definition of the signal(S) operation
signal(S) {
S++;
}

S
1

Operating System Concepts – 9th Edition 5.31 Silberschatz, Galvin and Gagne ©2013
Semaphore for Ordering the processes
Definition of the wait(S) operation
wait(S) {
while (S <= 0); // busy-wait
S--;
}
Definition of the signal(S) operation
signal(S) {
S++;
}

S1 S2
0 0

Operating System Concepts – 9th Edition 5.32 Silberschatz, Galvin and Gagne ©2013
Semaphore for Resource Management
Definition of the wait(S) operation
wait(S) {
while (S <= 0); // busy-wait
S--;
}
Definition of the signal(S) operation
signal(S) {
S++;
}

S
3

Operating System Concepts – 9th Edition 5.33 Silberschatz, Galvin and Gagne ©2013
Deadlock and Starvation
Deadlock – two or more processes are waiting indefinitely for an
event that can be caused by only one of the waiting processes
Let S and Q be two semaphores initialized to 1
P0 P1
wait(S); wait(Q);
wait(Q); wait(S);
... ...
signal(S); signal(Q);
signal(Q); signal(S);

Starvation – indefinite blocking


A process may never be removed from the semaphore queue in which it is
suspended
Priority Inversion – Scheduling problem when lower-priority process
holds a lock needed by higher-priority process
Solved via priority-inheritance protocol

Operating System Concepts – 9th Edition 5.34 Silberschatz, Galvin and Gagne ©2013
Classical Problems of Synchronization

Classical problems used to test newly-proposed synchronization


schemes
Bounded-Buffer Problem
Readers and Writers’ Problem
Dining-Philosophers Problem

Operating System Concepts – 9th Edition 5.35 Silberschatz, Galvin and Gagne ©2013
Bounded-Buffer Problem
➢ Bounded buffer problem, which is also called the producer-consumer
problem, is one of the classical problems of synchronization.
➢ There is a buffer of n slots, and each slot is capable of storing one
unit of data. There are two processes running, namely, producer and
consumer, which are operating on the buffer.
➢ A producer tries to insert data into an empty slot of the buffer. A
consumer tries to remove data from a filled slot in the buffer.
➢ Both processes won't produce the expected output if they are being
executed concurrently.
➢ There needs to be a way to make the producer and consumer work
in an independent manner.

Operating System Concepts – 9th Edition 5.36 Silberschatz, Galvin and Gagne ©2013
Bounded-Buffer Problem

Bounded buffer: size ‘N’


Access entry 0… N-1, then “wrap around” to 0 again

Producer process writes data to buffer


Must not write more than ‘N’ items more than consumer “ate”

Consumer process reads data from buffer


Should not try to consume if there is no data

0 1 N-1

In Out

Operating System Concepts – 9th Edition 5.37 Silberschatz, Galvin and Gagne ©2013
Bounded-Buffer Problem
Consumer()
Counting Semaphore
Full = 0; INDEX VAL Down(Full);
Empty = N; Down(S);
0 A
Binary Semaphore S = 1; 1 B Item = Buffer[OUT];
2 C OUT = (OUT + 1)mod n;
Producer_item(item p)
3 Up(S);
Down(Empty); 4 Up(Empty);
Down(S);
5
Buffer[IN] = item; 6 IN OUT
IN = (IN + 1)mod n; 7 3 0

Up(S);
Up(Full);

Operating System Concepts – 9th Edition 5.38 Silberschatz, Galvin and Gagne ©2013
Readers-Writers Problem

There is a shared resource which should be accessed by multiple processes. There are two
types of processes in this context. They are reader and writer. Any number of readers can
read from the shared resource simultaneously, but only one writer can write to the shared
resource. When a writer is writing data to the resource, no other process can access the
resource. A writer cannot write to the resource if there are non zero number of readers
accessing the resource at that time.
A data set is shared among a number of concurrent processes
Readers – only read the data set; they do not perform any updates
Writers – can both read and write
Problem – allow multiple readers to read at the same time
Only one single writer can access the shared data at the same time
Several variations of how readers and writers are considered – all involve some form of
priorities
Shared Data
Data set
Semaphore rw_mutex initialized to 1
Semaphore mutex initialized to 1
Integer read_count initialized to 0

Operating System Concepts – 9th Edition 5.39 Silberschatz, Galvin and Gagne ©2013
Readers-Writers Problem

Models access to a database


A reader is a thread that needs to look at the database but
won’t change it.
A writer is a thread that modifies the database
Example: making an airline reservation
When you browse to look at flight schedules the web site is
acting as a reader on your behalf
When you reserve a seat, the web site has to write into the
database to make the reservation

Operating System Concepts – 9th Edition 5.40 Silberschatz, Galvin and Gagne ©2013
Readers-Writers Problem (Cont.)

Operating System Concepts – 9th Edition 5.41 Silberschatz, Galvin and Gagne ©2013
Dining-Philosophers Problem

Operating System Concepts – 9th Edition 5.42 Silberschatz, Galvin and Gagne ©2013
Dining-Philosophers Problem
S0 S1 S2 S3 S4
1 1 1 1 1

Operating System Concepts – 9th Edition 5.43 Silberschatz, Galvin and Gagne ©2013
Dining-Philosophers Problem
S0 S1 S2 S3 S4
1 1 1 1 1

The structure of Philosopher i:


do {
Philosophers SP SP wait (S[i] );
wait (S[ (i + 1) % 5] );
P0 S0 S1
P1 S1 S2 // eat
P2 S2 S3
P3 S3 S4 signal (S[i] );
P4 S4 S0 signal (S[ (i + 1) % 5] );

// think

} while (TRUE);

Operating System Concepts – 9th Edition 5.44 Silberschatz, Galvin and Gagne ©2013
Dining-Philosophers Problem

The dining philosopher's problem is another classic synchronization problem


which is used to evaluate situations where there is a need of allocating multiple
resources to multiple processes.
Philosophers spend their lives alternating thinking and eating
Don’t interact with their neighbors, occasionally try to pick up 2 chopsticks (one
at a time) to eat from bowl
Need both to eat, then release both when done
In the case of 5 philosophers
Shared data
 Bowl of rice (data set)
 Semaphore chopstick [5] initialized to 1

Operating System Concepts – 9th Edition 5.45 Silberschatz, Galvin and Gagne ©2013
Dining-Philosophers Problem Algorithm

Operating System Concepts – 9th Edition 5.46 Silberschatz, Galvin and Gagne ©2013
End of Chapter 5

Operating System Concepts – 9th Edition Silberschatz, Galvin and Gagne ©2013

You might also like