Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

21cs56 - Operating Systems Chapter 6 - (Module2) Process Synchronization

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

21cs56 – Operating systems

Chapter 6- (Module2)
PROCESS SYNCHRONIZATION

Department of Information Science and Engg 1


Transform Here
Synchronization
❑Background
❑The Critical-Section Problem
❑Peterson’s Solution
❑Synchronization Hardware
❑Semaphores
❑Classic Problems of Synchronization
❑Monitors

Department of Information Science and Engg 2


Transform Here
Basic Concepts
❑A cooperating process is one that can affect or be affected by
other processes executing in the system.
❑Cooperating processes can either directly share a logical
address space (that is, both code and data) or be allowed to
share data only through files or messages.
❑Concurrent access to shared data may result in data
inconsistency.
❑To maintain data consistency, various mechanisms is required
to ensure the orderly execution of cooperating processes that
share a logical address space.

Department of Information Science and Engg 3


Transform Here
Producer and Consumer Problem
❑A Producer process produces information that is consumed by
consumer process.
❑To allow producer and consumer process to run concurrently, A
Bounded Buffer can be used where the items are filled in a buffer
by the producer and emptied by the consumer.
❑The original solution allowed at most BUFFER_SIZE - 1 item in
the buffer at the same time.
❑To overcome this deficiency, an integer variable counter,
initialized to 0 is added.
❑counter is incremented every time when a new item is added
to the buffer and is decremented every time when one item
removed from the buffer.

Department of Information Science and Engg 4


Transform Here
Producer
while (true) {
/* produce an item and put in nextProduced */
while (count == BUFFER_SIZE)
; // do nothing
buffer [in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
count++;
}

Department of Information Science and Engg 5


Transform Here
Consumer

while (true) {
while (count == 0)
; // do nothing
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
/* consume the item in nextConsumed
}

Department of Information Science and Engg 6


Transform Here
Department of Information Science and Engg
Transform Here
Race Condition
When the producer and consumer routines shown above are
correct separately, they may not function correctly when
executed concurrently.
Illustration:
Suppose that the value of the variable counter is currently 5
and that the producer and consumer processes execute the
statements "counter++" and "counter--" concurrently.
The value of the variable counter may be 4, 5, or 6 but the only
correct result is counter == 5, which is generated correctly if
the producer and consumer execute separately.

Department of Information Science and Engg 8


Transform Here
But the result can also be 4 or 6

Department of Information Science and Engg


Transform Here
Race Condition
count++ could be implemented as
register1 = count
register1 = register1 + 1
count = register1
count-- could be implemented as
register2 = count
register2 = register2 - 1
count = register2
Consider this execution interleaving with “count = 5” initially:
S0: producer execute register1 = count {register1 = 5}
S1: producer execute register1 = register1 + 1 {register1 = 6}
S2: consumer execute register2 = count {register2 = 5}
S3: consumer execute register2 = register2 - 1 {register2 = 4}
S4: producer execute count = register1 {count = 6 }
S5: consumer execute count = register2 {count = 4}

Department of Information Science and Engg


Transform Here
To guard against the race condition, we need to ensure that only one process at a
time can be manipulating the variable counter.🡺 need process synchronization

Department of Information Science and Engg


Transform Here
Critical Section Problems
❑Consider a system consisting of n processes {Po, P1 , ...
,Pn-1}.
❑Each process has a segment of code, called a critical
section in which the process may be changing common
variables, updating a table, writing a file, and soon
❑The important feature of the system is that, when one
process is executing in its critical section, no other process
is to be allowed to execute in its critical section.
❑That is, no two processes are executing in their critical
sections at the same time.
❑The critical-section problem is to design a protocol that
the processes can use to cooperate.
Department of Information Science and Engg 12
Transform Here
General structure of a typical process
❑Each process must request
permission to enter its critical
section.
❑The section of code implementing
this request is the entry section.
❑The critical section may be followed
by an exit section.
❑The remaining code is the
reminder section

Department of Information Science and Engg 13


Transform Here
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 - If no process is executing in its critical section and there exist


some processes that wish to enter their critical section, then only those
processes that are not executing in their remainder sections can participate in
deciding which will enter its critical section next. And the selection 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 relative speed of the N processes
Department of Information Science and Engg 14
Transform Here
Two general approaches are used to handle critical sections in
operating systems:
1. preemptive kernels A preemptive kernel allows a process to be
preempted while it is running in kernel mode.
2. nonpreemptive kernels A nonpreemptive kernel does not allow a
process running in kernel mode to be preempted.
• A kernel-mode process will run until it exits kernel mode,
blocks, or voluntarily yields control of the CPU.
• So is free from race condition.

Updating kernel data structures:


List of open files
Maintaining memory allocation
Maintaining process lists

Department of Information Science and Engg 15


Transform Here
PETERSON'S SOLUTION
❑This is a classic software-based solution to the critical-section
problem.
❑There are no guarantees that Peterson's solution will work
correctly on modern computer architectures.
❑ Peterson's solution provides a good algorithmic description of
solving the critical section problem and illustrates some of the
complexities involved in designing software that addresses the
requirements of
✔mutual exclusion,
✔progress,
✔bounded waiting.

Department of Information Science and Engg 16


Transform Here
PETERSON'S SOLUTION
Peterson's solution is restricted to two processes that alternate
execution between their critical sections and remainder sections.
Peterson's solution requires the two processes to share two data
items:
int turn;
boolean flag[2];
turn: The variable turn indicates whose turn it is to enter its
critical section. Ex: if turn == i, then process Pi is allowed to execute
in its critical section
flag: The flag array is used to indicate if a process is ready to
enter its critical section. Ex: if flag [i] is true, this value indicates
that Pi is ready to enter its critical section.

Department of Information Science and Engg 17


Transform Here
PETERSON'S SOLUTION
✔To enter the critical section, process Pi first
sets flag [i] to be true and then sets turn to do {
the value j, thereby asserting that if the other flag[i] = TRUE;
process wishes to enter the critical section, turn = j;
it can do so.
while (flag[j] && turn == j);
✔If both processes try to enter at the same
critical section
time, turn will be set to both i and j at
roughly the same time. Only one of these flag[i] = FALSE;
assignments will last, the other will occur remainder section
but will be over written immediately. } while (TRUE);
✔The eventual value of turn determines which
of the two processes is allowed to enter its
critical section first
Department of Information Science and Engg 18
Transform Here
To prove that solution is correct, then we need to
show that
1. Mutual exclusion is preserved
2. Progress requirement is satisfied
3. Bounded-waiting requirement is met

Department of Information Science and Engg 19


Transform Here
To prove Mutual exclusion
Each pi enters its critical section only if either flag [j] == false or turn ==i.
If both processes can be executing in their critical sections at the same
time, then flag [0] == flag [1]==true.
However, at that time, flag [j] == true and turn == j, and this condition will
persist as long as Pi is in its critical section, as a result, mutual exclusion is
preserved.

Department of Information Science and Engg 20


Transform Here
To prove Progress and Bounded-waiting
❑A process Pi can be prevented from entering the critical
section only if it is stuck in the while loop with the condition
flag [j] ==true and turn=== j; this loop is the only one
possible.
❑If Pj is not ready to enter the critical section, then flag [j]
==false, and Pi can enter its critical section.
❑If Pj has set flag [j] = true and is also executing in its while
statement, then either turn === i or turn ===j.
❑ If turn == i, then Pi will enter the critical section.
❑ If turn== j, then Pj will enter the critical section.

Department of Information Science and Engg 21


Transform Here
Disadvantages of Peterson’s solution

1. No guarantee on all modern computer


architectures.
2. If two processes try to enter at the same time,
turn will be set to both I and j at the same time

Department of Information Science and Engg 22


Transform Here
SYNCHRONIZATION HARDWARE
❑Use specific hardware instructions do {
to solve critical section problem. acquire lock
critical section
❑The solution to the critical-section
problem requires a simple tool-a release lock
lock. remainder
❑Race conditions are prevented by section
requiring that critical regions be
} while (TRUE);
protected by locks.

Department of Information Science and Engg 23


Transform Here
How to solve a critical section problem in a uniprocessor environment?
❑The critical-section problem could be solved simply in a uniprocessor environment
if interrupts are prevented from occurring while a shared variable was being
modified. 🡺 disable interrupts
❑Current sequence of instructions would executed without preemption
❑ But this solution is not as feasible in a multiprocessor environment.
Time consuming process to disable interrupts.
Message passing may delay entry into critical section

Department of Information Science and Engg 24


Transform Here
TestAndSet ( ) and Swap( ) instructions
Many modern computer systems provide
special atomic hardware instructions
that allow to test and modify the content
of a word or to swap the contents of two
words atomically, that is, as one
uninterruptible unit.

Special instructions such as Properties:


▪ Executed atomically
TestAndSet () 🡺 tests memory word and
▪ Returns the original value of passed
sets the value parameter
Swap()🡺 swaps the contents of 2 memory ▪ Set the new value of passed
parameter to true
words and is executed atomically.
Atomic🡺 non-interruptible

Department of Information Science and Engg 25


Transform Here
Mutual Exclusion with TestAndSet()
• Shared Boolean variable lock, initialized to FALSE

Department of Information Science and Engg 26


Transform Here
Definition of Swap() Instruction
void Swap (boolean *a, boolean *b)
Executed atomically
{
boolean temp = *a; Operates on the contents of 2
*a = *b; words and swaps the contents
*b = temp:
}
Shared Boolean variable lock initialized to FALSE; Each process has a local
Boolean variable key 🡺 set to TRUE
Solution:
do {
Implementation of Mutual-exclusion
key = TRUE;
while ( key == TRUE) with Swap() instruction
Swap (&lock, &key );
// critical section
lock = FALSE;
// remainder section
} while (TRUE);
Department of Information Science and Engg 27
Transform Here
Bounded-waiting Mutual Exclusion with TestandSet()
do {
waiting[i] = TRUE; Two types of global data structures:
key = TRUE; Boolean waiting[n];
while (waiting[i] && key) Boolean lock;
key = TestAndSet(&lock);
waiting[i] = FALSE;
// critical section • The data structure are initialized to
j = (i + 1) % n; false.
while ((j != i) && !waiting[j]) • To prove that the mutual exclusion
j = (j + 1) % n; requirement is met, Note that
if (j == i) process Pi can enter its critical
lock = FALSE; section only if either
else waiting[i]==false or key==false
waiting[j] = FALSE;
// remainder section
} while (TRUE);

Department of Information Science and Engg


Transform Here
Compare_and_swap() Instruction
• CAS works on 3 operands.
• Thus, if two CAS instructions are
executed simultaneously (each
on a different core), they will be
executed sequentially in some
arbitrary order.
• The operand value is set to new
value only if the expression
(*value == expected) is true.
• Shared Boolean variable lock
initialized to 0;
• The first process that invokes
compare and swap() will set lock
to 1. It will then enter its critical
section,

Department of Information Science and Engg 29


Transform Here
Department of Information Science and Engg 30
Transform Here
Bounded-waiting with
compare-and-swap

Department of Information Science and Engg 31


Transform Here
Atomic Variables

Department of Information Science and Engg


Transform Here
Department of Information Science and Engg
Transform Here
Department of Information Science and Engg 34
Transform Here
Department of Information Science and Engg 35
Transform Here
Semaphore

Department of Information Science and Engg 36


Transform Here
Semaphore

Department of Information Science and Engg 37


Transform Here
Semaphore Usage Example

Department of Information Science and Engg 38


Transform Here
Semaphore Implementation

Department of Information Science and Engg 39


Transform Here
Semaphore Implementation with no Busy waiting

Department of Information Science and Engg 40


Transform Here
Semaphore Implementation with no Busy waiting

Department of Information Science and Engg 41


Transform Here
Semaphore Implementation with no Busy waiting

Department of Information Science and Engg 42


Transform Here
Problems with Semaphores

Department of Information Science and Engg 43


Transform Here
Classical Problems of Synchronization
Bounded-Buffer Problem

Readers and Writers Problem

Dining-Philosophers Problem

Department of Information Science and Engg 44


Transform Here
Bounded-Buffer Problem also called as producer consumer
problem
The producer and consumer share the common data structures

Department of Information Science and Engg 45


Transform Here
Bounded-Buffer Problem

Department of Information Science and Engg 46


Transform Here
Bounded-Buffer Problem

Department of Information Science and Engg 47


Transform Here
Readers-Writers Problem
❑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.
❑To ensure that these difficulties do not arise, we require that the writers have
exclusive access to the shared database.
❑This synchronization problem is referred to as the readers-writers problem.

Department of Information Science and Engg 48


Transform Here
Two Variation
1. requires that no reader will be kept waiting unless a
writer has already obtained permission to use the
shared object.
2. requires that, once a writer is ready, that writer
performs its write as soon as possible.

Department of Information Science and Engg 49


Transform Here
Readers-Writers Problem (Cont.)

Department of Information Science and Engg 50


Transform Here
Readers-Writers Problem (Cont.)

Department of Information Science and Engg 51


Transform Here
Readers-Writers Problem (Cont.)

Department of Information Science and Engg 52


Transform Here
Readers-Writers Problem Variations

Department of Information Science and Engg 53


Transform Here
Dining-Philosophers Problem
Consider five philosophers who spend their lives
thinking and eating.
The philosophers share a circular table surrounded
by five chairs, each belonging to one philosopher.
In the center of the table is a bowl of rice, and the
table is laid with five single chopsticks.
A philosopher gets hungry and tries to pick up the
two chopsticks that are closest to her
A philosopher may pick up only one chopstick at a
time.
When a hungry philosopher has both her chopsticks
at the same time, she eats without releasing the
chopsticks.
When she is finished eating, she puts down both
chopsticks and starts thinking again.

Department of Information Science and Engg 54


Transform Here
Solution
One simple solution is to represent each chopstick with a
semaphore.
A philosopher tries to grab a chopstick by executing a wait() operation on
that semaphore.
She releases her chopsticks by executing the signal() operation on the
appropriate semaphores.
Thus, the shared data are
semaphore chopstick[5];
where all the elements of chopstick are initialized to 1.

Department of Information Science and Engg 55


Transform Here
Department of Information Science and Engg 56
Transform Here
Dining-Philosophers Problem Algorithm

Department of Information Science and Engg 57


Transform Here
What is the problem with the above?
Relies too much on programmers not making
mistakes (accidental or deliberate)
Incorrect use of semaphore operations:
▪ signal (mutex) …. wait (mutex)
▪ wait (mutex) … wait (mutex)
▪ Omitting of wait (mutex) or signal (mutex) (or
both)

Department of Information Science and Engg 58


Transform Here
Department of Information Science and Engg 59
Transform Here
End of Chapter 6

Department of Information Science and Engg 60


Transform Here
If the CPU scheduling policy is priority non-preemptive, calculate
the average waiting time and average turn around time. (Higher
number represents higher priority)
Process Id Arrival time Burst time Priority
P1 0 4 2

P2 1 3 3

P3 2 1 4

P4 3 5 5

P5 4 2 5

Department of Information Science and Engg 61


Transform Here

You might also like