Module3 Process Synchronization
Module3 Process Synchronization
OPERATING SYSTEMS
Subject code : CSC 404
Subject In-charge
Nidhi Gaur
Assistant Professor
email: [email protected]
Concurrency vs Parallelism
• If multiple processes are running concurrently, they each take
turns working towards accomplishing their goals.
• If multiple processes are running in parallel, they are all
accomplishing their tasks simultaneously and independently
of each other.
Processes
Interprocess communication
Concurrent processes
Background
▪ Concurrent access to shared data may result in data
inconsistency
▪ Maintaining data consistency requires mechanisms to ensure
the orderly execution of cooperating processes
▪ Suppose that we wanted to provide a solution to the producer-
consumer problem that fills the buffer. We can do so by having
an integer count that keeps track of the buffer size. Initially,
count is set to 0. It is incremented by the producer after it
produces a new item and is decremented by the consumer
after it consumes an item.
Producer/consumer
Producer
while (true) {
Consumer
while (true) {
while (count == 0)
; // do nothing
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
count--;
Race Condition
A situation where several
• count++ could be implemented as processes access and manipulate
the same data concurrently and
register1 = count outcome of the execution
register1 = register1 + 1
count = register1 depends on the particular order in
which the access takes place.
• 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}
Mutual Exclusion
purposes. Distribution and modifications of the content is prohibited.
Critical section
To design a protocol
that the processes
can use to cooperate.
Mutual exclusion
• Software approaches
First Attempt
Busy Waiting
• Process is always checking to see if it
can enter the critical section
• Process can do nothing productive until
it gets permission to enter its critical
section
First Attempt
Second Attempt
▪ Each process can examine the other’s status but
cannot alter it.
▪ When a process wants to enter the critical section it
checks the other processes first.
▪ If no other process is in the critical section, it sets its
status for the critical section
▪ This method does not guarantee mutual exclusion
▪ Each process can check the flags and then proceed to
enter the critical section at the same time
Second Attempt
A boolean vector flag is defined.
P0→flag[0] ; P1→flag[1]
Consider sequence:
P0 executes while & finds flag[1] set to false.
P1 executes while & finds flag[0] set to false.
P0 sets flag[0] true & enters critical section.
P1 sets flag[1] to true & enters critical section.
Both process in critical section, program incorrect.
Solution is not independent of execution speed.
Second Attempt
Third Attempt
Fourth Attempt
Fourth Attempt
Fourth Attempt
Consider the sequence:
P0 sets flag[0] to true.
P1 sets flag[1] to true.
P0 checks flag[1].
P1 checks flag[0].
P0 sets flag[0] to false.
P1 sets flag[1] to false.
This condition is live lock.
This is not deadlock as any alteration in speed will break the
sequence.
Live lock
• A common instance of Live lock is that when two
persons meet face to face in a corridor, and both move
aside to let the other pass. They end up moving in the
same direction simultaneously. So, they are failed to
cross each other.
Deadlock
Deadlock :
• a scenario in which one thread/process holds
some resource, A, and is blocked, waiting for
some resource, B, to become available, while
another thread/process holds resource B and is
blocked, waiting for resource A to become
available.
• When a deadlock occurs, no progress is made
within a program.
St. Francis Institute of Technology Operating System
Department of Computer Engineering Nidhi Gaur
The material in this presentation belongs to St. Francis Institute of Technology and is solely for educational
purposes. Distribution and modifications of the content is prohibited.
Deadlock
Deadlock vs Livelock
Correct Solution
• Each process gets a turn at the critical section
• If a process wants the critical section, it sets
its flag and may have to wait for its turn
P0
TURN?
FLAG?
P1
CRITICAL SECTION
Peterson’s Solution
purposes. Distribution and modifications of the content is prohibited.
while (true) {
flag[i] = TRUE; // Pi is interested in CS
turn = j; // TURN is of Pj
while ( flag[j] && turn == j); // check status of Pj
/*do nothing*/
/* CRITICAL SECTION*/
flag[i] = FALSE;
/* REMAINDER SECTION*/
Peterson’s Solution
Semaphores
Semaphores
Semaphores
purposes. Distribution and modifications of the content is prohibited.
procedure
Semaphore
• Semaphore S – an integer variable
• Two standard operations modify S: wait() and signal()
– Originally called P() and V()
• Can only be accessed via two indivisible (atomic) operations
– wait (S) {
while S <= 0
; // no-op
S--;
}
– signal (S) {
S++;
}
Semaphore as General
Synchronization Tool
Counting semaphore – An integer value can range over an
unrestricted domain
Binary semaphore – An integer value can range only between 0
and 1; a resource having single instance can use it.
–Also mutex is a binary semaphore, in which process that locks
the CS can unlock it. Provides mutual exclusion.
–Semaphore S; // initialized to 1
–wait (S);
Critical Section
signal (S);
Semaphore Implementation
purposes. Distribution and modifications of the content is prohibited.
waiting
With each semaphore there is an associated waiting
queue. Each entry in a waiting queue has two data
items:
– value (of type integer)
– pointer to next record in the list
Two operations:
–block – place the process invoking the operation on
the appropriate waiting queue.
–wakeup – remove one of processes in the waiting
queue and place it in the ready queue.
Semaphores
• Wait may cause a thread to block (i.e., when the counter is
zero), it has a similar effect of the lock operation of a mutex
lock.
• A Signal may release waiting threads, and is similar to the
unlock operation. In fact, semaphores can be used as mutex
locks. Consider a semaphore S with initial value 1. Then, Wait
and Signal correspond to lock and unlock:
Semaphore
• Semaphore: Count
PID 1 PID 2 count
sem=pm_seminit(1); 1
pm_wait(sem); 0
pm_wait(sem); -1
(critical)
pm_signal(sem); 0
pm_wait(sem); -1
(critical)
pm_signal(sem); 0
pm_wait(sem); -1
(critical)
pm_signal(sem); 0
St. Francis Institute of Technology Operating System
Department of Computer Engineering Nidhi Gaur
The material in this presentation belongs to St. Francis Institute of Technology and is solely for educational
purposes. Distribution and modifications of the content is prohibited.
Semaphores
Producer/Consumer Problem
Infinite Buffer
Producer/Consumer
The producer-consumer problem (also known as the bounded-
buffer problem) is a classical example of a multi-process
synchronization problem
The problem describes two processes, the producer and the
consumer, who share a common, fixed-size buffer. The
producer's job is to generate a piece of data, put it into the
buffer and start again. At the same time the consumer is
consuming the data (i.e. removing it from the buffer) one
piece at a time. The problem is to make sure that the
producer won't try to add data into the buffer if it's full and
that the consumer won't try to remove data from an empty
buffer.
Producer/Consumer
• The solution for the producer is to go to sleep if the buffer is
full. The next time the consumer removes an item from the
buffer, it wakes up the producer who starts to fill the buffer
again.
• In the same way, the consumer goes to sleep if it finds the
buffer to be empty. The next time the producer puts data into
the buffer, it wakes up the sleeping consumer. The solution
can be reached by means of inter-process communication,
typically using semaphores. An inadequate solution could
result in a deadlock where both processes are waiting to be
awakened.
Producer/Consumer
• Incorrect implementation
int itemCount
procedure producer() {
while (true) {
item = produceItem()
if (itemCount == BUFFER_SIZE) {
sleep()
}
putItemIntoBuffer(item)
itemCount = itemCount + 1
•
if (itemCount == 1) {
wakeup(consumer)
}
}
Operating System
}
St. Francis Institute of Technology
Department of Computer Engineering Nidhi Gaur
The material in this presentation belongs to St. Francis Institute of Technology and is solely for educational
purposes. Distribution and modifications of the content is prohibited.
Producer/Consumer
• procedure consumer() {
• while (true) {
• if (itemCount == 0) {
• sleep()
• }
•
• item = removeItemFromBuffer()
• itemCount = itemCount - 1
•
• if (itemCount == BUFFER_SIZE - 1) {
• wakeup(producer)
• }
•
• consumeItem(item)
• St. Francis
} Institute of Technology Operating System
• }
Department of Computer Engineering Nidhi Gaur
The material in this presentation belongs to St. Francis Institute of Technology and is solely for educational
purposes. Distribution and modifications of the content is prohibited.
Producer/Consumer
• procedure consumer() {
• while (true) {
The problem with this solution is
that it contains a race condition • if (itemCount == 0) {
that can lead into a deadlock. • sleep()
Consider the following scenario:
• }
➢ The consumer has just read
the variable itemCount, •
noticed it's zero and is just • item =
about to move inside the if- removeItemFromBuffer()
block. • itemCount = itemCount - 1
➢ Just before calling sleep, the •
consumer is interrupted and • if (itemCount ==
the producer is resumed. BUFFER_SIZE - 1) {
➢ The producer creates an item, • wakeup(producer)
puts it into the buffer, and
increases itemCount. • }
•
• consumeItem(item)
• }
St. Francis Institute of Technology
Department of Computer Engineering • }Operating
Nidhi Gaur
System
The material in this presentation belongs to St. Francis Institute of Technology and is solely for educational
purposes. Distribution and modifications of the content is prohibited.
Producer/Consumer
• procedure consumer() {
• while (true) {
➢ Because the buffer was empty
prior to the last addition, the • if (itemCount == 0) {
producer tries to wake up the
consumer. • sleep()
➢ Unfortunately the consumer • }
wasn't yet sleeping, and the •
wakeup call is lost. When the • item =
consumer resumes, it goes to removeItemFromBuffer()
sleep and will never be • itemCount = itemCount - 1
awakened again. This is
because the consumer is only •
awakened by the producer • if (itemCount ==
when itemCount is equal to 1 BUFFER_SIZE - 1) {
• wakeup(producer)
• }
•
• consumeItem(item)
St. Francis Institute of Technology
•Operating}System
Department of Computer Engineering
•Nidhi}Gaur
The material in this presentation belongs to St. Francis Institute of Technology and is solely for educational
purposes. Distribution and modifications of the content is prohibited.
Producer/Consumer
• Using semaphores
semaphore fillCount = 0
semaphore emptyCount = BUFFER_SIZE
procedure producer() {
while (true) {
item = produceItem()
down(emptyCount)
putItemIntoBuffer(item)
up(fillCount)
}
}
procedure consumer() {
while (true) {
down(fillCount)
item = removeItemFromBuffer()
up(emptyCount)
consumeItem(item)
}
Operating System
} St.Department
Francis Institute of Technology
of Computer Engineering Nidhi Gaur
The material in this presentation belongs to St. Francis Institute of Technology and is solely for educational
purposes. Distribution and modifications of the content is prohibited.
Producer/Consumer
• The solution above works fine when there is only one producer and
consumer. Unfortunately, with multiple producers or consumers this
solution contains a serious race condition that could result in two or more
processes reading or writing into the same slot at the same time.
If the procedure can be executed concurrently by multiple producers,
the following scenario is possible:
• Two producers decrement emptyCount
• One of the producers determines the next empty slot in the buffer .
Second producer determines the next empty slot and gets the same
result as the first producer
• Both producers write into the same slot
Producer/Consumer
• To overcome this problem, we need a way to make sure that
only one producer is executing putItemIntoBuffer() at a time.
In other words we need a way to execute a critical section
with mutual exclusion. To accomplish this we use a binary
semaphore called mutex. Since the value of a binary
semaphore can be only either one or zero, only one process
can be executing between down(mutex) and up(mutex).
Producer/Consumer
The solution for multiple producers and consumers is given
below:
There are three semaphores.
• Full, used for counting the number of slots that are full;
• empty, used for counting the number of slots that are empty;
• mutex, used to enforce mutual exclusion.
Producer/Consumer
purposes. Distribution and modifications of the content is prohibited.
BufferSize = 3;
Producer()
{
int widget;
Producer/Consumer
Consumer()
{
int widget;