0% found this document useful (0 votes)
62 views79 pages

Unit3 IPC SSPDF 2024 02 20 10 42 29

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
62 views79 pages

Unit3 IPC SSPDF 2024 02 20 10 42 29

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Inter Process Communication

Unit-3
Operating System/01CE1401

Department of Computer Engineering


Prof. Shilpa Singhal
Topics Covered
● Interprocess Communication (IPC)
● Models of IPC
● Race Condition
● Process Synchronization
● Sections of Program
● Critical Section
● Conditions of Critical Section
● Process Synchronization Solutions
o Software Solutions
o Hardware Solutions
● Classical IPC Problems
o Bounder Buffer/Producer Consumer Problem
o Readers and writers
o Dining philosophers
o Sleeping barber
Introduction to IPC

Processes in system can be independent or cooperating.


• Independent processes: cannot affect or be affected by the execution of another
process.
• Cooperating processes: can affect or be affected by the execution of another
process.

Cooperating processes need inter process communication mechanisms.


Introduction to IPC

Inter-process communication (IPC) is a set of methods for the exchange of data


among multiple threads in one or more processes.

Processes may be running on one or more computers connected by a network.

IPC may also be referred to as inter-thread communication and inter-application


communication.
Why IPC?

There are several reasons for providing an environment that allows process
cooperation:

• Information sharing
• Computational speedup
• Modularity
• Convenience
Issues of process cooperation

• Data corruption
• Deadlock
• Increased complexity
• Requires processes to synchronize their processing
Models for IPC
There are two models for IPC
a)Message Passing (Process A send the message to Kernel and then Kernel send that
message to Process B)
b)Shared Memory (Process A put the message into Shared Memory and then Process B
read that message from Shared Memory)
Race Condition

• Race conditions arise in software when separate


processes or threads of execution depend on some shared state.

• A Race condition is an undesirable situation that occurs when a


device or system attempts to perform two or more operations at the
same time.
• Operations upon shared states are critical sections that
must be mutually exclusive. Failure to do so opens up the
possibility of corrupting the shared state.
• But, because of the nature of the device or system, the operations
must be done in the proper sequence to be done correctly.
Race Condition-Example

In is local variable containing pointer


to next free slot
Out is local variable pointing to next
file to be printed

Figure : Two processes want to access


shared memory at the same time
Race Condition

• Race condition: Situations like this where processes access the same data
concurrently and the outcome of execution depends on the particular order
in which the access takes place is called race condition.

• Situation where two or more processes are reading or writing some


shared data and the final result depends on who runs precisely when.
How to avoid Races???

• Mutual exclusion–only one process at a time can use a shared


variable/file
• Critical regions-shared memory which leads to races
• Exact instruction execution order cannot be predicted
• Resource (file, memory, data etc…) sharing

• Solution- Ensure that two processes can’t be in the critical region at the
same time
Process Synchronization

• Process Synchronization is the task of coordinating the execution of


processes in a way that no two processes can have access to the same shared
data and resources.

• It is specially needed in a multi-process system when multiple processes are


running together, and more than one processes try to gain access to the same
shared resource or data at the same time.
How Process Synchronization works

For Example, process A changing the data in a memory location while


another process B is trying to read the data from the same memory location.
There is a high probability that data read by the second process will be
erroneous.
Sections of a Program

Here, are four essential elements of a program :


• Entry Section: It is part of the process which decides the entry of a particular
process.
• Critical Section: This part allows one process to enter and modify the shared
variable.
• Exit Section: Exit section allows the other process that are waiting in the Entry
Section, to enter into the Critical Sections. It also checks that a process that
finished its execution should be removed through this Section.
• Remainder Section: All other parts of the Code, which is not in Critical, Entry,
and Exit Section, are known as the Remainder Section.
Critical Section/Region

• The critical section problem is one of the classic problems in Operating Systems.
• In operating systems, there are processes called cooperative processes that
share and access a single resource. In these kinds of processes, the problem of
synchronization occurs. The critical section problem is a problem that deals
with this synchronization.

• The part of program where shared memory is accessed is called the critical
region or critical section.

• If no two processes are ever in their critical regions at the same time then we
could avoid race condition.
Critical Section-Example
PseudoCode for Critical Section
while(true)
{

// entry section

process_entered=1;

//loop until process_enterd in 0

while(process_entered);

// critical section

// exit section

process_entered=0

// remainder section

}
Conditions of Critical Section Problem

The solution to the critical section problem must satisfy the following conditions −

1. (Primary)Mutual Exclusion: Mutual exclusion implies that only one process can be inside the
critical section at any time. If any other processes require the critical section, they must wait
until it is free.

2. (Primary)Progress: Progress means that if a process is not using the critical section, then it
should not stop any other process from accessing it. In other words, any process can enter a
critical section if it is free.

3. (Secondary)Bounded Waiting: Bounded waiting means that each process must have a limited
waiting time. It should not wait endlessly to access the critical section.
4. (Secondary) Architectural Neutrality: Our mechanism must be architectural natural. It means
that if our solution is working fine on one architecture then it should also run on the other ones
as well
Mutual Exclusion

For shared memory, share files & other shared things there should be some
way to prohibit one process from reading & writing the shared data at the
same time.

Need to make sure that if one process is using a shared resource; the other
process will be stopped from doing the same thing.
In other words… There should be Mutual Understanding(Mutual
Exclusion).
Mutual Exclusion-Example
Mutual Exclusion-Example
Process Synchronization Solutions
1.Lock Variable

2.Strict Alteration or
TURN variable
Software Solutions
3.Peterson’s Solution

Process 4.Semaphores
Synchronization
Solutions
1.Disabling Interrupts

2.Test and Set Lock


Hardware Solutions
(TSL)

3.Swap Instruction
Solutions to Critical Section Problem

1. Lock variables(Software)
2. Strict alternation or TURN variable (Software)
3. Peterson's solution(Software)
4. Semaphores(Software)
5. Disabling interrupts(Hardware)
6. The TSL instruction (Hardware)
7. XCHG or SWAP instruction(Hardware)
1.Lock variables

A software solution-everyone shares a lock

• Lock Variable is software mechanism implemented at user


mode.
• It works on Multiple Processes.
• When lock is 0, process turns it to 1 and enters critical region
• When exit critical region, turn lock to 0
• Value=0 means critical section is free.
1.Lock variables
int LOCK=0
ENTRY_SECTION(int Process)
{
While(LOCK=O)
LOCK=1
}

CRITICAL SECTION

EXIT_SECTION(int process)
{
LOCK=0
}
REMAINDER SECTION()
1.Lock variables Disadvantage

• The Lock Variable doesn’t provide mutual exclusion in some cases.


• 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.
2.Strict Alternation or TURN variable

• Turn Variable or Strict Alternation Approach is the software mechanism


implemented at user mode. It is a busy waiting solution which can be
implemented only for two processes.
• In this approach, A turn variable is used which is actually a lock.
• This approach can only be used for only two processes.
• A process can enter in the critical section only in the case when the value of
the turn variable equal to the PID of the process.
2.Strict Alternation or TURN variable
• Integer variable ‘turn’ keeps track of whose turn is to enter the critical section.
• Initially turn =0
• Process 0 inspects turn, finds it to be 0, and enters in critical section.
• Process 1 also finds it to be 0 and therefore sits in loop
continually testing ‘turn’ to see when it becomes 1.
• countinusoly testing a variable until some value appears is called busy
waiting.
• When process 0 exits from critical region it sets turn
to 1 and now process 1 can find it to be 1 and enters in to critical region.
• In this way, both the processes get alternate turn to
enter critical region.
2.Strict Alternation or TURN variable
while (TRUE) { while (TRUE) {
Non-Critical Region Non-Critical Region
while ( turn != 0); /* loop */ while ( turn != 1); /* loop */
Critical_region(); Critical_region();
turn =1; turn =0;
Non-Critical Region Non-Critical Region
} }
Figure Figure
(a)Process 0 (b)Process 1

A proposed solution to the critical region problem. (a) Process 0. (b) Process 1.
Assuming Turn=0 means P0 can execute
Turn=1 means P1 can execute
2.TURN variable-Advantage

The actual problem of the lock variable approach was the fact that the process was
entering in the critical section only when the lock variable is 1. More than one
process could see the lock variable as 1 at the same time hence the mutual
exclusion was not guaranteed there.

This problem is addressed in the turn variable approach. Now, A process can enter
in the critical section only in the case when the value of the turn variable equal to
the PID of the process.
2.TURN variable-Advantage

This solution Provides:

Mutual Exclusion
The strict alternation approach provides mutual exclusion in every case. This procedure
works only for two processes

It does not Provide:


Progress
Progress is not guaranteed in this mechanism. If P0 doesn't want to get enter into the
critical section on its turn then P1 got blocked for infinite time. P1 has to wait for so
long for its turn since the turn variable will remain 0 until P0 assigns it to 1.
3.Peterson’s Solution

• Peterson's solution is a classic software based solution to the critical section


problem.
• It may not work on modern computer architecture.
• Peterson’s solution is restricted to two processes that alternate execution between
their critical sections and remainder sections.
• Let the two process be Pi and Pj.
• Peterson’s solution requires two data items to be shared between two processes turn
and flag variable.
• The flag variable indicates if a process is ready to enter the critical region. Its a
Boolean variable.
• The turn variable denotes which process turn is now to enter the critical region.
• The critical section problem ensures that no two processes change or modify a
resource's value simultaneously.
3.Peterson’s Solution
3.Peterson’s Solution

Peterson's solution provides a solution to the following problems,

1. It ensures that if a process is in the critical section, no other process must be allowed to enter it.
This property is termed mutual exclusion.

2. If more than one process wants to enter the critical section, the process that should enter the
critical region first must be established. This is termed progress.
3. There is a limit to the number of requests that processors can make to enter the critical region,
provided that a process has already requested to enter and is waiting. This is termed bounding.

4. It provides platform neutrality as this solution is developed to run in user mode, which doesn't
require any permission from the kernel.
4.Disabling Interrupts(Hardware Solution)
• Idea: process disables interrupts, enters critical region, enables interrupts
when it leaves critical region.
• It is hardware solution which runs on kernel mode.
• It ensures Mutual Exclusion and Progress.
• Not frequently used.
Problems

• Process might never enable interrupts, crashing system


• Won’t work on multi-core (multiprocessor/with two or more CPUs)chips as
disabling interrupts only effects only the CPU that executed the
disabling instruction.
5.Test & Set Lock(TSL)(Hardware)
• Test and set algorithm is a hardware based solution.
• There is a lock variable that is shared and can have two values 0(Unlock) and
1(Lock).
• Before entering the critical section a process enquires about the lock.
• If it is locked the process waits till it becomes free.
• If it is not locked, it will set the lock and enters the critical section.
5.Test & Set Lock(TSL)(Hardware)
5.Test & Set Lock(TSL)(Hardware)

Lock value = 0 means the critical section is currently vacant and no process is present inside it.
Lock value = 1 means the critical section is currently occupied and a process is present inside it.
6.XCHG or SWAP instruction
• Swap function uses two boolean variables lock and key. Both lock and key variables
are initially initialized to false.
• Swap algorithm is the same as lock and set algorithm.
• The Swap algorithm uses a temporary variable to set the lock to true when a process
enters the critical section of the program.

Link : https://www.scaler.com/topics/operating-system/synchronization-hardware-in-
os/
6.XCHG or SWAP instruction
6.XCHG or SWAP instruction

In the code above when a process P1 enters the critical section of the program it first executes the while loop

while(key)
{
swap(lock,key);
}

As key value is set to true just before the for loop so swap(lock, key) swaps the value of lock and key. Lock
becomes true and the key becomes false. In the next iteration of the while loop breaks and the process, P1
enters the critical section.
Analysis

Solution Mutual Exclusion Progress Bounded Waiting

Lock Variable No No No

Strict Alteration Yes No Yes

Peterson’s Solution Yes Yes Yes

Disabling Interrupt Yes Yes No

Test and Set Lock Yes Yes No

Swap Instruction Yes No No


What’s wrong with Peterson, TSL,XCHG?

• When a process wants to enter its critical region, it checks to see if the entry is
allowed.
• If it is not, the process just sits in a tight loop waiting until it is allowed to
enter.

Problem : Busy waiting-waste of CPU time!


7.Semaphores
7.Semaphores
7.Semaphores
A semaphore is a variable that provides a simple but
useful abstraction for controlling access (of shared resource) by multiple
processes to a common resource in a parallel programming or multi user
environment.

• Semaphore is an integer variable

• A useful way to think of a semaphore is as a record of how many units of a


particular resource are available, coupled with operations to safely (i.e., without
race conditions) adjust that record as units are required or become free, and, if
necessary, wait until a unit of the resource becomes available.

Link:
https://www.youtube.com/watch?v=XDIOC2EY5JE&list=PLBlnK6fEyqRiVhbXDGLXDk_OQAeuVcp2O&index=
60
Semaphores : wait() & signal() operations

• A simple way to understand wait() and signal() operations is:


• wait(): Decrements the value of semaphore variable by 1. If the value
becomes negative or 0, the process executing wait() is blocked (like sleep),
i.e., added to the semaphore's queue.
• signal(): Increments the value of semaphore variable by 1. After the
increment, if the pre-increment value was negative (meaning there are
processes waiting for a resource), it transfers a blocked process from the
semaphore's waiting queue to the ready queue. (like Wake up)
Classic IPC Problems

1. Bounder Buffer/Producer Consumer Problem


2. Readers and writers
3. Dining philosophers
4. Sleeping barber
1.The Producer- Consumer Problem

• It is also known as Bounded Buffer Problem.(multi- process synchronization


problem).
• Consider two processes Producer and Consumer , who share common, fixed size
buffer.
• Producer :produce and puts information into the buffer
• Consumer: consume(remove) this information from buffer.
1.The Producer- Consumer Problem
1.The Producer- Consumer Problem
Producer Consumer with Semaphores

3 semaphores: full, empty and mutex


• Full counts full slots (initially 0)
• Empty counts empty slots (initially N)
• Mutex control access to critical region (protects variable
which contains the items produced and consumed)

Link : https://www.youtube.com/watch?v=Qx3P2wazwI0
Producer Consumer with Semaphores
mutex 1
0

void producer (void)


empty 3
4
{ int item;
#define N 4
typedef int semaphore; while (true) full 10

semaphore mutex=1; {
item Item 1
item=produce_item();
semaphore empty=N;
down(&empty);
semaphore full=0;
down(&mutex); Producer Buffer Consumer
insert_item(item); 1
up(&mutex); 2
up(&full); 3
} } 4
Producer Consumer with Semaphores

mutex 10
void consumer (void)
{ int item;
empty 4
3
while (true)
{ full 01
down(&full);
down(&mutex); item
item=remove_item(item);
up(&mutex); up(&empty); Producer Buffer Consumer
consume_item(item); 1 Item 1
} 2
3
} 4
Producer Consumer Problem

• Trouble arises when the producer wants to put a new item in the buffer,
but it is already full.
• And consumer wants to remove a item from buffer, but it is already empty.

Solution for producer: The producer either go to sleep or discard the data if
buffer is full to be awakened when the consumer has removed one or more
items.
Solution for consumer: if the consumer wants to remove an item from the
buffer and sees that the buffer is empty, it goes to sleep until the producer puts
something in the buffer and wakes it up.
2.Readers and writers

• Multiple readers can concurrently read from the data base.

• But when updating the db, there can only be one writer (i.e.,
no other writers and no readers either)

Link:
https://www.youtube.com/watch?v=p2XDhW5INOo
2.Readers and writers
2.Readers and writers
2.Readers and writers
2.Readers and writers using Semaphore
void Reader (void)
typedef int semaphore;
{ while (true)
semaphore mutex=1; void Writer (void)
{ down(&mutex);
semaphore db=1; rc=rc+1; {
int rc=0; if(rc==1) while (true)
down(&db); {
up(&mutex); think_up_data();
read_data_base(); down(&db);
down(&mutex); write_data_base();
rc=rc-1; up(&db);
if(rc==0) }
up(&db);
}
up(&mutex);
use_read_data();
} }
3.Dining philosophers Problem
Philosophers eat and think.
1. To eat, they must first
acquire a left fork and
then a right fork (or
vice versa).
2. Then they eat.
3. Then they put down the forks.
4. Then they think.
5. Go to 1.

Link: https://www.youtube.com/watch?v=FYUi-u7UWgw
3.Dining philosophers Problem
3.Dining philosophers Problem
3.Dining philosophers Problem
3.Possible Methods to avoid Deadlock
3.Dining philosophers using Semaphore
#define N 5
#define LEFT (i+N-1)%5
#define RIGHT (i+1)%5
#define THINKING 0
#define HUNGRY 1
#define EATING 2
typedef int semaphore;
int state[N];
semaphore mutex=1;
semaphore s[N];
3.Dining philosophers Solution using
semaphore
void philosopher (int i) void test (i)
{ {
while (true) if (state[i]==HUNGRY &&
{ state[LEFT]!=EATING &&
state[RIGHT]!=EATING)
think();
{
take_forks(i);
state[i]=EATING;
eat();
up (&s[i]);
put_forks(i);
}
}
}
}
3.Dining philosophers using Semaphore

void put_forks (int i)


void take_forks (int i)
{
{ down(&mutex);
down(&mutex);
state[i]=THINKING;
state[i]=HUNGRY;
test(LEFT);
test(i); up(&mutex);
test(RIGHT);
down(&s[i]);
up(&mutex);
}
}
4.Sleeping barber problem

• One barber, one barber chair, and N seats for waiting.


• No customers so barber sleeps.
• Customer comes in & wakes up barber.
• More customers come in.
 If there is an empty seat, they take a seat.
 Otherwise, they leave.

Link: https://www.youtube.com/watch?v=OvJFpsN5czg&t=228s
4.Sleeping barber problem
4.Sleeping barber problem
4.Sleeping barber problem
4.Sleeping barber Solution using Semaphore
4.Sleeping barber Solution using Semaphore
4.Sleeping barber Solution using Semaphore
4.Sleeping barber Solution using Semaphore
Problems in Sleeping Barber Problem

Starvation: Barber may pick any random customer from waiting room and
Customer who came first might wait for long.

Solution: A queue can be used in the waiting room to add customers in FIFO
order.
4.Sleeping barber Solution using Semaphore
#define CHAIRS 5 void barber(void) void customer(void)
{ {
typedef int semaphore;
while (TRUE) { down(&mutex);
semaphore customers = 0;
down(&customers); if (waiting < CHAIRS) {
semaphore barbers = 0;
down(&mutex); waiting = waiting + 1;
semaphore mutex = 1;
waiting = waiting - 1; up(&customers);
int waiting = 0;
up(&barbers); up(&mutex);
up(&mutex); down(&barbers);
cut_hair(); get_haircut();
} } else {
} up(&mutex);
}
}

You might also like