0% found this document useful (0 votes)
10 views

Unit 3 Presentation

Uploaded by

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

Unit 3 Presentation

Uploaded by

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

Unit III (Concurrency Control) - Syllabus

Mutual Exclusion
Process/thread Synchronization and Mutual Exclusion: Principles of
Concurrency, Requirements for Mutual Exclusion, Mutual Exclusion: Hardware
Support, Operating System Support (Semaphores and Mutex), Programming
Language Support (Monitors). Classical synchronization problems:
Readers/Writers Problem, Producer and Consumer problem, Inter-process
communication (Pipes, shared memory: system V).
Deadlock
Principles of Deadlock, Deadlock Modeling, Strategies to deal with deadlock:
The Ostrich Algorithm, Deadlock Prevention, Deadlock Avoidance, Deadlock
detection and recovery, An Integrated Deadlock Strategy, Example: Dining
Philosophers Problem. Unix Concurrency Mechanism
Department of Information Technology, VIIT, Pune-48
Principles of Concurrency

• Concurrency is the interleaving of processes in time to give the


appearance of simultaneous execution.
• It differs from parallelism, which offers genuine simultaneous
execution
• Execution of multiple processes at the same time.
• Concurrency is the tendency for things to happen at the same time
in a system.
• Processes that coexist on the memory at a given time are called
concurrent process.
• Concurrency results in sharing of resources result in problems like
deadlocks and resources starvation.
Department of Information Technology, VIIT, Pune-48
Advantages of Concurrency :
• Running of multiple applications –
It enable to run multiple applications at the same time.
• Better resource utilization –
It enables that the resources that are unused by one application can
be used for other applications.
• Better average response time –
Without concurrency, each application has to be run to completion
before the next one can be run.
• Better performance –
When one application uses only the processor and another
application uses only the disk drive then the time to run both
applications concurrently to completion will be shorter than the time
to run each application seperately.
Department of Information Technology, VIIT, Pune-48
Drawbacks of Concurrency :
• It is required to protect multiple applications from one another.
• Additional performance overheads and complexities in operating systems are
required for coordinating multiple applications, switching among applications.
• Sometimes running too many applications concurrently leads to severely
degraded performance.
• Sharing global resources –
Sharing of global resources safely is difficult. If two processes both make use of a
global variable and both perform read and write on that variable, then the order
in which various read and write are executed is critical.
• Optimal allocation of resources –
It is difficult for the operating system to manage the allocation of resources
optimally.
• Locking the channel –
It may be inefficient for the operating system to simply lock the channel and
prevents its use by other processes.
Department of Information Technology, VIIT, Pune-48
Process Synchronization

• On the basis of synchronization, processes are categorized as one of the


following two types:
• Independent Process: The execution of one process does not affect the
execution of other processes.
• Cooperative Process: A process that can affect or be affected by other
processes executing in the system. A cooperative process shares
something like
 Variable
 Memory location
 File
 Code
 Resource
Department of Information Technology, VIIT, Pune-48
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.
• This can lead to the inconsistency of shared data. So the change
made by one process not necessarily reflected when other
processes accessed the same shared data.
• To avoid this type of inconsistency of data, the processes need to
be synchronized with each other.
Department of Information Technology, VIIT, Pune-48
Process Synchronization:

Department of Information Technology, VIIT, Pune-48


Issues in Concurrency :
• Race Condition -
A Race Condition typically occurs when two or more threads try to read,
write and possibly make the decisions based on the memory that they are
accessing concurrently.
• Blocking –
Processes can block waiting for resources. A process could be blocked for
long period of time waiting for input from a terminal. If the process is
required to periodically update some data, this would be very undesirable.
• Starvation –
It occurs when a process does not obtain service to progress.
• Deadlock –
It occurs when one processes ‘A’ is holding some resource ‘R1’and asking
for another resource ‘R2’ which is hold by another process ‘B’ and process
B is asking for resource ‘R1’
Department of Information Technology, VIIT, Pune-48
Race Condition:
• If a process1 is trying to read the data present in a memory location
while another process2 is trying to change the data present at the same
location, there is a high chance that the data read by the process1 will
be incorrect.
• In the critical section, a race condition occurs when the end result of
multiple thread executions varies depending on the sequence in which
the threads execute.
Int shared = 5;
P1 P2
Int x= shared int y=shared
X++ y--
Sleep(1) sleep(1)
Shared=x shared=y
Department of Information Technology, VIIT, Pune-48
Issues with Race Condition:
• Race condition may lead to
 Deadlock,
 Loss of data,
 Data inconsistency
 Undesirable results and output

Department of Information Technology, VIIT, Pune-48


Critical Section
• The regions of a program that access shared resources and may
cause race conditions are called critical section.
• To avoid race condition among the processes, we need to assure that
only one process at a time can execute within the critical section.
• Critical Section is the part of a program which tries to access shared
resources. That resource may be any resource in a computer like a
memory location, Data structure, CPU or any IO device.
• The critical section cannot be executed by more than one process at
the same time; operating system faces the difficulties in allowing and
disallowing the processes from entering the critical section.
• The critical section problem is used to design a set of protocols
which can ensure that the Race condition among the processes will
never arise.
Department of Information Technology, VIIT, Pune-48
Starvation
• Starvation is the problem that occurs when high priority processes
keep executing and low priority processes get blocked for indefinite
time.
• In heavily loaded computer system, a steady stream of higher-priority
processes can prevent a low-priority process from ever getting the CPU.
• Starvation may occur if there are not enough resources to provide to
every process as required.
• If random selection of processes is used then a process may wait for a
long time because of non-selection.
• In starvation resources are continuously utilized by high priority
processes.
• Problem of starvation can be resolved using Aging. In Aging priority of
long waiting processes is gradually increased.
Department of Information Technology, VIIT, Pune-48
Synchronization Mechanism
Following 4 conditions/rules must be satisfied to achieve process
synchronization

• Mutual Exclusion Mandatory


• Progress
• Bounded wait Not mandatory
• No assumptions related to hardware speed but desired

Department of Information Technology, VIIT, Pune-48


Mutual Exclusion
• A Solution designed by Dijkstra for the race condition
• “no two processes can exist in the critical section at any given point
of time”.

Department of Information Technology, VIIT, Pune-48


Mutual Exclusion
Process P1 Process P2

Int main() Int main()


-------- --------
-------- --------
Non Non
critical critical
section section

-------- --------
-------- --------

Entry code Entry code


critical critical
section section

Exit code Exit code

Department of Information Technology, VIIT, Pune-48


Progress and Bounded waiting

Progress

Progress means that if one process doesn't need to


execute into critical section then it should not stop other
processes to get into the critical section.

Bounded waiting

We should be able to predict the waiting time for every


process to get into the critical section. The process must
not be endlessly waiting for getting into the critical section.

Department of Information Technology, VIIT, Pune-48


Solution to Race Condition

Department of Information Technology, VIIT, Pune-48


Solution – 1: Peterson Solution
• In this solution, when a process is executing in a critical state, then the
other process only executes the rest of the code. This method also helps
to make sure that only a single process runs in the critical section at a
specific time.
• Assume there are N processes (P1, P2, … PN) and every process at some
point of time requires to enter the Critical Section
• A FLAG[] array of size N is maintained which is by default false. So,
whenever a process requires to enter the critical section, it has to set its
flag as true. For example, If Pi wants to enter it will set FLAG[i]=TRUE.
• Another variable called TURN indicates the process number which is
currently wating to enter into the CS.
• The process which enters into the critical section while exiting would
change the TURN to another number from the list of ready processes.
Department of Information Technology, VIIT, Pune-48
Solution – 1: Peterson Solution
Entry_section(process) 0 1
{ interested F F
Int other;
Other=1-process; turn 0

Interested[process]=TRUE;
Turn=process
While(interested[other]==TRUE && turn==process)
}
//*********Critical section**********//
Exit_section(process)
{
Interested[process]=false;
}
Department of Information Technology, VIIT, Pune-48
Solution – 2: Semaphore
• One of the method to remove the race condition
• Technique to manage concurrent processes by using a simple
integer value, which is known as a semaphore.
• Semaphore is simply an integer variable that is shared between
threads.
• This variable is used to solve the critical section problem and to
achieve process synchronization
• Two types-
• 1. Counting Semaphore – semaphore value can vary from -∞ to
+∞
• 2. Binary Semaphore - – semaphore value can vary from 0 to 1

Department of Information Technology, VIIT, Pune-48


Solution – 2: Semaphore
• Types of Semaphore in OS
1. Binary Semaphores
2. Counting Semaphores

1.Binary Semaphore
• Value of the semaphore can only be either 0 or 1.
• If the value of Semaphore is 1, the process can enter into the critical section ,
• If the value is 0, the process cannot enter into the critical section of the code.
• When a process is using the critical section, we change the Semaphore value to 0,
• When a process is not using it, or we can allow a process to access the critical
section, we change the value of semaphore to 1.
• Binary semaphore is also called mutex lock.

Department of Information Technology, VIIT, Pune-48


Solution – 2: Semaphore
Entry_section()
Down(semaphore s) or wait(semaphore s) or P(semaphore s)
{
If(s value==1)
{
s.value=0;
successfull entry into critical section;
}
Else
{
Block this process and place in suspend list
Sleep()
}
}
Department of Information Technology, VIIT, Pune-48
Solution – 2: Semaphore
Exit_section()
Up(semaphore s) or signal(semaphore s) or V(semaphore s)
{
If(suspend list is empty)
{
s.value=1
}
Else
{
s.value=1
select a process from suspend list
wakeup()
}
}

Department of Information Technology, VIIT, Pune-48


Solution – 2: Semaphore
2. Counting Semaphore
Counting semaphores are generally used when the number of
instances of a resource is more than 1, and multiple processes can
access the resource.
 Semaphore count is the number of available resources.
 Using these Semaphores, we can coordinate access to resources
and here the Semaphore count is the number of resources
available.
 The value of the Semaphore is anywhere between -∞ to +∞
 However, if the value is 0, it means that there aren't any resources
that are available or the critical section is already being accessed
by a number of processes and cannot be accessed by more
processes.
Department of Information Technology, VIIT, Pune-48
Solution – 2: Semaphore

Down(semaphore s) Up (semaphore s)
{ {
s.value=s.value-1 s.value=s.value+1
If(s.value<0)
If(s.value<=0)
{
Suspend()
{
Sleep() Select a process from suspend list
} Wakeup()
Else }
Return }
}

Department of Information Technology, VIIT, Pune-48


Solution – 3: Monitors
• Code inside monitors can only be executed by one process at a time.
• It is a group of procedures and conditional variables assembled into a particular form of
module or package.
• Monitors are a synchronization tool used in process synchronization to manage access to
shared resources and coordinate the actions of numerous threads or processes.
• When opposed to low-level primitives like locks or semaphores, they offer a higher-level
abstraction for managing concurrency.
• It has a shared variable and a collection of procedures executing on the shared variable.
• A process may not directly access the shared data variables, and procedures are
required to allow several processes to access the shared data variables simultaneously.
• A program cannot access the monitor's internal variable if it is running outside the
monitor.
• At any particular time, only one process may be active in a monitor. Other processes that
require access to the shared variables must queue and are only granted access after the
previous process releases the shared variables.
Department of Information Technology, VIIT, Pune-48
Solution – 3: Monitors
Monitor monitor_Name
{
variables_declaration;
condition_variables;

procedure p1{ ... };


procedure p2{ ... };
...
procedure pn{ ... };

{
initializing_code;
}

Department of Information Technology, VIIT, Pune-48


Classical synchronization problems:

1. Producer and Consumer problem


2. Readers/Writers Problem

Department of Information Technology, VIIT, Pune-48


Producer-Consumer Problem using Semaphores

Department of Information Technology, VIIT, Pune-48


Producer-Consumer Problem using Semaphores
• The Producer-Consumer problem is a classic multi-process
synchronization problem
• there is one Producer who produces things, and there is one Consumer
who consumes the products which are produced by the producer. The
producers and consumers share the same fixed-size memory buffer.
• The Producer's role is to produce data, store it in the buffer, and then
generate data again. The Consumer's task is to consume the data from
the buffer.
• When the consumer is consuming an item from the buffer, the
producer should not add items into the buffer, and vice versa. As a
result, only one producer or consumer should access the buffer at a
time.

Department of Information Technology, VIIT, Pune-48


Producer-Consumer Problem using Semaphores
• Let's consider that there are n slots in the buffer, and each slot
may store one unit of data. On the buffer, there are two processes
running: producer and consumer.

• A producer tries to fill an empty space in the buffer with data. A


consumer attempts to retrieve data from that buffer slot. If those
two processes run concurrently, as you may have anticipated, they
will not give the desired outcome.

Department of Information Technology, VIIT, Pune-48


Challenges in Producer-Consumer Problem using Semaphores

• The producer should generate data only if the buffer is not full.
When the buffer is filled, the producer should not be able to add
any more data to it.
• When the buffer is not empty, the consumer can consume the
data. The consumer should not be able to take any data from the
buffer if it is empty.
• The buffer should not be used by both the producer and the
consumer at the same time.

Department of Information Technology, VIIT, Pune-48


Producer-Consumer Problem
Producer code

Department of Information Technology, VIIT, Pune-48


Producer-Consumer Problem
Consumer code

Department of Information Technology, VIIT, Pune-48


Producer-Consumer Problem

Department of Information Technology, VIIT, Pune-48


Producer Consumer Problem

Buffer has total 8 spaces out of which the first 5 are filled,
in = 5(pointing next empty position) and
out = 0(pointing first filled position).

Let's start with the producer who wanted to produce an element " F ",
according to code it will enter into the producer() function, while(1) will
always be true, itemP = F will be tried to insert into the buffer, before
that while(count == n); will evaluate to be False.

• Buffer[in] = itemP → Buffer[5] = F. ( F is inserted now)


• in = (in + 1) mod n → (5 + 1)mod 8→ 6, so, in = 6; (next empty buffer)
• After insertion of F, Buffer looks like this
Department of Information Technology, VIIT, Pune-48
Producer Consumer Problem

Where out = 0, but in = 6

Since count = count + 1; is divided into


three parts:
1. Load Rp, m[count] → will copy count value

which is 5 to register Rp.


2. Increment Rp → will increment Rp to 6.
3. store m[count] Rp
Suppose just after Increment and before the
execution of third line Context Switch occurs
and code jumps to consumer code. . .

Department of Information Technology, VIIT, Pune-48


Producer Consumer Problem

• Consumer Code:
• Now starting consumer who wanted to consume the first element " A
", according to code it will enter into the consumer() function, while(1)
will always be true, while(count == 0); will evaluate to be False( since
the count is still 5, which is not equal to 0.
itemC = Buffer[out]→ itemC = A ( since out is 0)
• out = (out + 1) mod n → (0 + 1)mod 8→ 1, therefore out = 1( first filled
position)
• A is removed now
• After removal of A, Buffer look like this
• Where out = 1, and in = 6

Department of Information Technology, VIIT, Pune-48


Producer Consumer Problem

Where out = 0, but in = 6


Since count = count - 1; is divided into three
parts:
1. Load Rc, m[count] → will copy count value
which is 5 to register Rp.
2. Decrement Rc → will decrement Rc to 4.
3. store m[count], Rc → count = 4.

Now the current value of count is 4


Suppose after this, Context Switch occurs back to the leftover part of producer
code. . .Since context switch at producer code was occurred after Increment and
before the execution of the third line (store m[count], Rp)
So we resume from here since Rp holds 6 as incremented value
Hence store m[count], Rp → count = 6

Department of Information Technology, VIIT, Pune-48


Producer Consumer Problem

Now the current value of count is 6, which is wrong as Buffer


has only 5 elements,

This condition is known as Race Condition and


Problem is Producer-Consumer Problem.

Department of Information Technology, VIIT, Pune-48


Solution to Producer-Consumer Problem using Semaphores

• To solve this problem, We employ three semaphore variables:-


• mutex - The lock is acquired and released using a mutex, a binary
semaphore.
• empty - empty is a counting semaphore that is initialized on the
basis of the number of slots present in the buffer, at first all the
slots are empty.
• full - a counting semaphore with a value of zero as its starting
value.
• At any particular time, the current value of empty denotes the
number of vacant slots in the buffer, while full denotes the number
of occupied slots.

Department of Information Technology, VIIT, Pune-48


Solution to Producer-Consumer Problem using Semaphores

• "in" used in a producer code represent the next empty buffer


• "out" used in consumer code represent first filled buffer
• Counting semaphore
• "empty" is counting semaphore which keeps a score of no. of empty
buffer
• "full" is counting semaphore which scores of no. of full buffer
• "S" is a binary semaphore BUFFER

Department of Information Technology, VIIT, Pune-48


Solution Producer-Consumer Problem using Semaphores

void producer( void ) void consumer(void)


{ {
down/wait ( empty ); wait ( empty );
down/wait(S); wait(S);
Produce_item(item P) itemC = buffer[ out ];
buffer[ in ] = item P; out = ( out + 1 ) mod n;
in = (in + 1)mod n signal(S);
up/signal(S); signal(empty);
up/signal(full); }
}
Binary semaphore = in = 1

Department of Information Technology, VIIT, Pune-48


Solution to Producer-Consumer Problem using Semaphores

• S = 1 (init. Value of Binary semaphore)


• in = 5 ( next empty buffer)
• out = 0 (first filled buffer)

Buffer has total 8 spaces out of which the first 5 are


filled,
in = 5 (pointing next empty position) and
out = 0 (pointing first filled position).

Department of Information Technology, VIIT, Pune-48


Solution to Producer-Consumer Problem using Semaphores

• Semaphores used in Producer Code:


• 1. wait(empty) - decreases the value of counting semaphore
variable empty by 1, that is when the producer produces some element then
the value of the space gets automatically decreased by one in the buffer. In
case the buffer is full, that is the value of the counting semaphore variable
"empty" is 0, then wait(empty); will trap the process (as per definition of
wait) and does not allow to go further.
• 2. wait(S) decreases the binary semaphore variable S to 0 so that no other
process which is willing to enter into its critical section is allowed.
• 3. signal(s) increases the binary semaphore variable S to 1 so that other
processes who are willing to enter into its critical section can now be allowed.
• 4. signal(full) increases the counting semaphore variable full by 1, as on
adding the item into the buffer, one space is occupied in the buffer and the
variable full must be updated.
Department of Information Technology, VIIT, Pune-48
Solution to Producer-Consumer Problem using Semaphores

• Semaphores used in Consumer Code:


• 5. wait(full) will decrease the value of the counting semaphore variable full
by 1, that is when the consumer consumes some element then the value of
the full space gets automatically decreased by one in the buffer. In case the
buffer is empty, that is the value of the counting semaphore variable full is 0,
then wait(full); will trap the process(as per definition of wait) and does not
allow to go further.
• 6. wait(S) decreases the binary semaphore variable S to 0 so that no other
process which is willing to enter into its critical section is allowed.
• 7. signal(S) increases the binary semaphore variable S to 1 so that other
processes who are willing to enter into its critical section can now be allowed.
• 8. signal(empty) increases the counting semaphore variable empty by 1, as
on removing an item from the buffer, one space is vacant in the buffer and
the variable empty must be updated accordingly.
Department of Information Technology, VIIT, Pune-48
Solution to the Producer-Consumer Problem using Semaphores

#include <pthread.h> sem_wait(&full);


#include <semaphore.h> pthread_mutex_lock(&mutex);
#include <stdlib.h> //Critical section starts
#include <stdio.h> int item = buffer[out];
printf("Consumer %d: Removed the item %d from %d\n",*((int *)cno),item, out);
/* out = (out+1)%BufferSize;
This program provides a possible solution for producer-consumer //Critical section ends
problem using mutex and semaphore. pthread_mutex_unlock(&mutex);
5 producers and 5 consumers are used to demonstrate the solution. sem_post(&empty);
*/ }
}
#define MaxItems 5 // Maximum items a producer can produce or a consumer can consume int main()
#define BufferSize 5 // Size of the buffer {
sem_t empty;//sem_t is a kind of unsigned char. pthread_t pro[5],con[5];// declaration of 5 producer threads and 5 consumer threads
sem_t full; // empty and full are two semaphore pthread_mutex_init(&mutex, NULL); // Mutex initialization
int in = 0; sem_init(&empty,0,BufferSize);//semaphore 1
int out = 0; //&empty -- address of semaphore, 0(we want to share this semaphore with other threads)
int buffer[BufferSize]; //BufferSize -- value we give to semaphore
pthread_mutex_t mutex; sem_init(&full,0,BufferSize); //semaphore 2

void *producer(void *pno) int a[5] = {1,2,3,4,5}; // used for numbering the producer and consumer
{
int item; for(int i = 0; i < 5; i++)
for(int i = 0; i < MaxItems; i++) {
{ pthread_create(&pro[i], NULL, (void *)producer, (void *)&a[i]);
item = rand(); // Produce a random item }
sem_wait(&empty);//initialized with 1 (entry code) for(int i = 0; i < 5; i++)
//wait, if there is no empty slots {
//The sem_wait() function decrements by one the value of pthread_create(&con[i], NULL, (void *)consumer, (void *)&a[i]);
//the semaphore. The semaphore will be decremented when }
//its value is greater than zero. If the value of the
//semaphore is zero, then the current thread will block for(int i = 0; i < 5; i++)
//until the semaphore's value becomes greater than zero. {
pthread_join(pro[i], NULL);
pthread_mutex_lock(&mutex); //if empty is > 0 acquire semaphore(lock) }
//Critical section starts for(int i = 0; i < 5; i++)
buffer[in] = item; {
printf("Producer %d: Inserted the item %d at %d\n", *((int *)pno),buffer[in],in); pthread_join(con[i], NULL);
in = (in+1)%BufferSize; }
//Critical section ends
pthread_mutex_unlock(&mutex);//release semaphore(unlock) pthread_mutex_destroy(&mutex);//This destroys the mutex object *mutex.
sem_post(&full); //same as signal operation(exit operation) sem_destroy(&empty);
//sem_post() increments the semaphore If the semaphore's value becomes greater sem_destroy(&full);
//than zero,then another process or thread blocked in a return 0;
//sem_wait call will be woken up and proceed to lock the
//semaphore. }
}
}
void *consumer(void *cno)
{
for(int i = 0; i < MaxItems; i++)
{
Department of Information Technology, VIIT, Pune-48
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.
• If a writer wants to write to the resource, it must wait until there are no
readers currently accessing that resource.

Department of Information Technology, VIIT, Pune-48


Solution to Readers/Writers Problem
• Here, we use one mutex m and a semaphore db.
• An integer variable read_count is used to maintain the number of readers
currently accessing the resource.
• The variable read_count is initialized to 0.
• The variables m and db are initialized to 1

Case Process 1 Process 2 Allowed / Not Allowed

Case 1 Reading Writing Not Allowed

Case 2 Writing Reading Not Allowed

Case 3 Writing Writing Not Allowed

Case 4 Reading Reading Allowed

Department of Information Technology, VIIT, Pune-48


Solution to Readers/Writers Problem

Int rc=0
Semaphore m=1, db=1 Down(m)
Void reader(void) //reader executes this rc - -
{ code If(rc==0) then up(db)
While(true) { Up(m)
Down(m) //same as wait() //Process data
rc++ }
If(rc==1) then down(db) }
Up(m) //same as signal void writter(void){
While(true){
Critical
section down(db)
Critical
section
//exit code starts
Up(db)
Department of Information}}Technology, VIIT, Pune-48
Inter process Communication
Inter-Process Communication is the mechanism by which cooperating process share data and
information. The mechanism that will allow them to exchange data and information are the
following:–
 Shared memory
 Message Passing
 Pipes

Department of Information Technology, VIIT, Pune-48


Inter process Communication using Pipes

Pipe is a communication medium between two or more related or interrelated processes.


Communication is achieved by one process writing into the pipe and other reading from the
pipe.
Pipe mechanism can be viewed with a real-time scenario such as filling water with the pipe
into some container say a bucket, and someone retrieving it, say with a mug.
The filling process is nothing but writing into the pipe and the reading process is nothing but
retrieving from the pipe.
This implies that one output (water) is input for the other (bucket).

Fd [0]
Fd [1]

Int pipe ( int fds[2] )


Returns ‘0’ for success and ‘-1’ for failure
Department of Information Technology, VIIT, Pune-48
Inter process Communication using Pipes

• This system call would create a pipe for one-way communication


i.e., it creates two descriptors, first one is connected to read from
the pipe and other one is connected to write into the pipe.
• Descriptor pipedes[0] is for reading and pipedes[1] is for writing.
• Whatever is written into pipedes[1] can be read from pipedes[0].
• This call would return zero on success and -1 in case of failure.
• To know the cause of failure, check with errno variable or perror()
function.

Department of Information Technology, VIIT, Pune-48


Inter process Communication using Pipes

• C program in notepad file

Department of Information Technology, VIIT, Pune-48


Deadlocks
A deadlock is a situation in which more than one process is blocked because it
is holding a resource and also requires some resource that is acquired by
some other process. Therefore, none of the processes gets executed.

Department of Information Technology, VIIT, Pune-48


Deadlocks
Basically in the Normal mode of Operation utilization of resources by a process
is in the following sequence:
• Request: Firstly, the process requests the resource. In a case, if the request
cannot be granted immediately(e.g: resource is being used by any other
process), then the requesting process must wait until it can acquire the
resource.
• Use: The Process can operate on the resource ( e.g: if the resource is a
printer then in that case process can print on the printer).
• Release: The Process releases the resource.

Department of Information Technology, VIIT, Pune-48


Necessary Conditions for Deadlock
The four necessary conditions for a deadlock to arise are as follows.

• Mutual Exclusion: Only one process can use a resource at any given time
i.e. the resources are non-sharable.
• Hold and wait: A process is holding at least one resource at a time and is
waiting to acquire other resources held by some other process.
• No preemption: The resource can be released by a process voluntarily i.e.
after execution of the process.
• Circular Wait: A set of processes are waiting for each other in a circular
fashion. For example, lets say there are a set of processes {P0 P1​, P2, P3​​}
such that P0​depends on P1, P1​depends on P2​, P2​depends on P3​and P3
depends on P0​.
• This creates a circular relation between all these processes and they have to
wait forever to be executed.

Department of Information Technology, VIIT, Pune-48


Methods of Handling Deadlocks in Operating System
• Deadlock Prevention
• The main aim of the deadlock prevention method is to violate any one condition among
the four; because if any of one condition is violated then the problem of deadlock will
never occur.
• As the idea behind this method is simple but the difficulty can occur during the physical
implementation of this method in the system.
• No Mutual Exclusion
• No Hold and Wait(try to give all the resources to a process)
• Allow Preemption,
• No circular wait – A process can request in increasing order of resource numbers. A
process cant not request a resource whose number is less than it’s previous resource
request number.
Ex. 1. Printer 2. Scanner 3. CPU 4.Memory
If Process P1 has requested for resource no. 3 initially, then it can not request resource no. 1
or 2 later on. Where as it can request for resource no. 4.

Department of Information Technology, VIIT, Pune-48


Methods of Handling Deadlocks in Operating System
• Deadlock Avoidance
• When a process requests a resource, the deadlock avoidance algorithm
examines the resource-allocation state.
• If allocating that resource sends the system into an unsafe state, then
request is not granted.
• Therefore, it requires additional information such as how many resources of
each type is required by a process. If the system enters into an unsafe state,
it has to take a step back to avoid deadlock.

Department of Information Technology, VIIT, Pune-48


Deadlock Detection and Recovery
• We let the system fall into a deadlock and if it happens, we detect it using a
detection algorithm and try to recover.
• Some ways of Detect and recovery are as follows.
• One way is to roll back, as the operating system keeps a record of the process
state and it can easily make a process roll back to its previous state due to
which deadlock situation can be easily eliminate.
• Second way is Resource Preemption: Resources are taken one by one from a
process and assigned to higher priority processes until the deadlock is
resolved.
• Abort all deadlocked processes
Abort one process at a time until the deadlock cycle is eliminated
In which order should we choose to abort?
1. Priority of the process
2. How long process has computed, and how much longer to completion
3. Resources the process has used
4. Resources process needs to complete
5. How many processes will need to be terminated
6. Is process interactive or batch?
Department of Information Technology, VIIT, Pune-48
Deadlock Detection and Recovery
• Deadlock Ignorance
• It is assumed that deadlock would never occur, OS simply ignores the
deadlock. This approach can be beneficial for those systems that are only used
for browsing or normal tasks but it is not perfect in order to remove the
deadlock from the operating system.
• This is an example of Ostrich method. It is a strategy of ignoring potential
problems assuming that they are extremely rare.

Department of Information Technology, VIIT, Pune-48


Ostrich algorithm
• The ostrich algorithm is a strategy of ignoring potential problems on the basis
that they may be exceedingly rare. It is named after the ostrich effect which is
defined as "to stick one's head in the sand and pretend there is no problem".
• It is used when it is more cost-effective to allow the problem to occur than to
attempt its prevention.
• This approach may be used in dealing with deadlocks in concurrent
programming, if they are believed to be very rare and the cost of detection or
prevention is high.
• For example, if each PC deadlocks once per years, a single reboot may be less
painful than the restrictions needed to prevent it.
• The Unix and windows operating systems take this approach.

Department of Information Technology, VIIT, Pune-48


Dining Philosophers Problem
• Consider there are five philosophers sitting around a circular dining table. The
dining table has five chopsticks and a bowl of rice in the middle as shown in
the below figure.

• At any instant, a philosopher is either eating or thinking. When a philosopher


wants to eat, he uses two chopsticks - one from their left and one from their
right. When a philosopher wants to think, he keeps down both chopsticks at
their original place.

Department of Information Technology, VIIT, Pune-48


Dining Philosophers Problem
• But if all five philosophers are hungry simultaneously, and each of them
pickup one chopstick(left), then a deadlock situation occurs because they will
be waiting for another(right) chopstick forever.

process P[i]

while true do
{
THINK();
takeFork(CHOPSTICK [i]); //left fork
takeFork (CHOPSTICK [i+1 mod 5]); //Right

EAT();
ReturnFork (CHOPSTICK [i]);
ReturnFork (CHOPSTICK [i+1 mod 5]);
} This works fine when the processes are executed serially, one after another.
But may form a race condition if two or more processes executes
concurrently
Department of Information Technology, VIIT, Pune-48
Dining Philosophers Problem

In this scenario, a typical deadloack situation can arise if all the


philosophers picks left chopstick and get preempted by another process.

P0S0 & S1
P1 S1 & S2
P2S2 & S3
P3S3 & S4
P4 S4 & S0

Department of Information Technology, VIIT, Pune-48


Dining Philosophers Problem
• Array of binary semaphore are used to initialize n-1 semaphore.
• Philosopher P0 requests for Semaphore S0(left) first and then S1(right)
• To overcome from deadlock, any one Philosopher’s sequence may be reversed

process P[i]
P0S0 & S1 while true do
P1 S1 & S2 {
P2S2 & S3 THINK();
P3S3 & S4 down/wait (CHOPSTICK [i]);
down/wait (CHOPSTICK [i+1 mod 5]);
P4 S4 & S0
EAT();
S0 & S4 up/Signal (CHOPSTICK [i]);
up/Signal (CHOPSTICK [i+1 mod 5]);
}

Department of Information Technology, VIIT, Pune-48


End of Unit 3

Department of Information Technology, VIIT, Pune-48

You might also like