OS Unit 3 Notes
OS Unit 3 Notes
Unit-3
Concurrency
Concurrency is the ability of a system to execute multiple tasks or processes simultaneously
without affecting the final outcome. It allows different parts of a program (or multiple programs)
to execute independently while still coordinating to produce a correct final outcome.
Concurrency in Programming
Programming languages and operating systems provide various mechanisms to handle
concurrency, such as:
Threads: Lightweight processes that can run concurrently.
Processes: Independent execution units with separate memory space.
Synchronization Mechanisms: Mutex locks, semaphores, and monitors to avoid race
conditions.
Page 1 of 25
Operating System (CS1103)
o Philosophers alternate between thinking and eating.
o A philosopher must have two chopsticks (left & right) to eat.
o A chopstick can only be held by one philosopher at a time.
o After eating, the philosopher must put both chopsticks back so that the
chopsticks become available to others.
o A philosopher can take the chopstick on their right or the one on their left as they
become available, but cannot start eating before getting both chopsticks.
o There is infinite noodles and infinite hunger, meaning philosophers will always
want to eat at some point.
The Problem:
How do we ensure that all philosophers get a fair chance to eat without deadlock (no progress) or
starvation (some never eat)? i.e., Ensure each philosophe can forever continue to alternate
between eating and thinking, assuming that no philosopher can know when others may want to
eat or think.
Page 2 of 25
Operating System (CS1103)
Example:
If we have 5 philosophers (P1, P2, P3, P4, P5), the chopsticks are assigned as:
P1 gets chopstick 1
P2 gets chopstick 2
P3 gets chopstick 3
P4 gets chopstick 4
P5 gets chopstick 5
If a philosopher wants to eat, they check if they already have both chopsticks.
If they don’t have both, they request the missing one from their neighbor.
The neighbor only gives the chopstick if it is "dirty".
Why?
If the chopstick is dirty, it means the neighbor already ate and should pass it.
If the chopstick is clean, the neighbor keeps it because they haven't eaten yet.
After eating, if a philosopher receives a request for a chopstick, they clean it and give
it to the requester.
No Deadlock: Philosophers do not all hold one chopstick forever. If they finish eating,
they return chopsticks fairly.
No Starvation: Every philosopher eventually gets both chopsticks and eats.
Fair Resource Sharing: A philosopher can’t hold onto chopsticks indefinitely.
Page 3 of 25
Operating System (CS1103)
Understanding Process Interactions & Concurrency
When multiple processes work together and execute simultaneously without proper coordination,
errors can happen. These errors are mainly due to unpredictable timing (also called timing
errors).
The mistake isn't caused by a single process; instead, it's due to how the processes are
interleaved (mixed together during execution).
Each process might work fine on its own, but when executed together, they may interfere
with each other, causing incorrect results.
For example, if two bank clerks update the same account balance at the same time without
coordination, they might overwrite each other’s changes, leading to incorrect balances.
Page 4 of 25
Operating System (CS1103)
Mutual Exclusion
Mutual exclusion ensures that only one process at a time can access a shared resource (such as a
variable or a printer). This prevents data corruption and ensures system reliability.
A critical section is a part of a program that accesses shared resources. It must be executed
without interruption to avoid errors.
How It Works:
ENTER CS: A process enters the critical section and starts executing.
EXECUTE CS: It modifies shared data while other processes wait.
EXIT CS: The process finishes and allows the next process to enter.
LOAD Rx, Count ; Load the shared variable Count into register Rx
If multiple processes execute this code without synchronization, they may read the same value
before updating it, causing incorrect results.
1. Prevents Data Corruption: Only one process modifies a shared variable at a time,
avoiding inconsistent values.
2. Ensures Proper Resource Use: Shared resources like printers won’t mix outputs from
different users.
3. Avoids Unpredictable Behavior: Ensures processes execute in an orderly manner.
Example: If two print jobs (one from a PDF and another from MS Word) run without mutual
exclusion, their contents may get mixed up on the same page.
Page 5 of 25
Operating System (CS1103)
Prevent deadlock (where no process can proceed) and starvation (where some processes
never get access).
Ensure processes don’t wait indefinitely to access the resource.
Every process follows these three steps while accessing a shared resource:
A Semaphore contains:
A counter (integer)
A waiting queue of processes
Two operations:
Page 6 of 25
Operating System (CS1103)
o wait(S)
o signal(S)
wait(S):
while (S <= 0) do ; // busy wait
S := S - 1; // acquire
signal(S):
S := S + 1; // release
Entry Protocol:
Exit Protocol:
while (true) {
// non-critical code
wait(S); // Enter CS
// critical section
signal(S); // Exit CS
// remaining code
}
Page 7 of 25
Operating System (CS1103)
Semaphore for Event Synchronization
Process P1 Process P2
s1; wait(sync);
signal(sync); s2;
Initialize sync = 0.
signal() and wait() are in different processes.
Operational Flow:
Types of Semaphores
2. Counting Semaphore
Value: >= 0
Used when multiple instances of a resource are available.
Page 8 of 25
Operating System (CS1103)
Queue-based Semaphore
wait(S):
if (S <= 0)
suspend process;
else
S--;
signal(S):
S++;
if (any process is waiting)
resume one;
Implementation Notes
Criticisms on Semaphores
Problem Description
Accidental Release Any process can signal a semaphore, even if it didn’t acquire it.
Recursive If a process calls wait() on a semaphore it already holds, it waits
Deadlock forever.
Process-Death If a process holding a semaphore crashes, it’s never released.
Deadlock
Priority Inversion Can happen when low-priority process holds a semaphore needed by
high-priority one (to be covered later).
Page 9 of 25
Operating System (CS1103)
Quiz1: Why should an error message be given to all the waiting processes while waking them
all up, when a process owning a Mutex dies while owning it?
a) Just to inform the next process which is going to own the Mutex and going to enter the CS
about the past event.
b) All the waiting processes are woken up so that all of them can enter the CS without any
restrictions.
c) Since the process owning the Mutex has died while inside the CS it could have left the CS in
an unstable state. All the waiting processes need to be informed, so that they take any
corrective action based on what the application warrants.
d) All the waiting processes can work together to restart the process which got killed while
owning the Mutex.
Correct Answer:
(c) - The CS may be in an unstable state; others must take corrective action.
Quiz2: Can a Mutex be used to synchronize occurrence of an event between two cooperating
processes?
a) Yes, similar to Semaphore, mutex can also be used to protect CS as well as synchronize
event between two processes.
b) No, it is not possible because OS knows which process is owning the Mutex and it cannot be
released by another process.
c) Yes, it is possible for a process to release the Mutex who is not the current owner of it,
because it is not being used by the application for CS and only for synchronization.
d) No, the OS does not have the knowledge of what is the purpose for which an application is
using the Mutex.
Page 10 of 25
Operating System (CS1103)
Correct Answers:
(b) OS restricts unlocking by non-owners.
(d) OS doesn’t know how application intends to use it.
Key Insight: Mutex is strictly for mutual exclusion, not event synchronization.
Mutex has strict lock/unlock pairing and ownership rules which cannot be used for
synchronization
It is not possible for another process to release it for signaling purposes.
OS does not distinguish between usage types (e.g., signaling vs. locking).
Keeps implementation simple and clean. (Doesn’t confuse mutual exclusion with
synchronization)
What is a Spinlock?
Real-world analogy
Page 11 of 25
Operating System (CS1103)
If the person inside takes too long — you're wasting time and energy. But if they come out
quickly — your aggressive waiting pays off.
Problem Statement
Two processes:
o Producer: Produces data and adds it to a shared buffer.
o Consumer: Takes data from the buffer and processes it.
Both run in infinite loops.
The buffer has a fixed size (N), hence the term bounded buffer.
Page 12 of 25
Operating System (CS1103)
Implementation Using Sleep() and Wakeup()
Code:
Initially count = 0;
Producer()
{
while (1)
{
produce_item();
if (count == N) sleep(); // Wait if buffer is full
count++;
if (count == 1) wakeup(consumer); // Wake up consumer if it was sleeping
}
}
Consumer()
{
while (1)
{
if (count == 0) sleep(); // Wait if buffer is empty
consume_item();
count--;
if (count == N - 1) wakeup(producer); // Wake up producer if space created
}
}
Scenario:
Cause:
Check (count == 0) and sleep() are not atomic (are different distinct step).
There’s a race condition between the test and the action.
Page 13 of 25
Operating System (CS1103)
Required Semaphores:
Semaphore Initialization:
mutex = 1
emptyCount = N
fullCount = 0
do {
produce_item();
wait(emptyCount); // Wait if buffer is full
wait(mutex); // Lock critical section
add_item_to_buffer();
do {
wait(fullCount); // Wait if buffer is empty
wait(mutex); // Lock critical section
remove_item_from_buffer();
consume_item();
} while (true);
Page 14 of 25
Operating System (CS1103)
Event Sequencing
Condition Action
Buffer Full Producer should block
Buffer Empty Consumer should block
0 < Buffer < N Both can proceed, with mutex
After getting the mutex, the producer can get blocked because the buffer is full.
When the consumer gets a chance to run, it sees that the buffer is full with data, it wants
to acquire the mutex to take an item out from the buffer, but it does not get it because the
producer holds it and is blocked now.
It will result in a Deadlock.
The sequence of mutex/semaphore calls is very critical.
Always:
Acquire semaphores in correct order.
Release semaphores properly.
Device Manager waits (P(s)) until interrupt arrives. Interrupt Handler executes and signals
(V(s)). Device Manager wakes up and processes data.
Page 15 of 25
Operating System (CS1103)
Deadlocks
A deadlock is a situation where multiple processes are waiting for resources that are held by
other processes, creating a cycle of dependency that prevents any process from proceeding.
In simple words, each process waits for a resource that is been assigned to another process, none
of the process gets executed since the resource it needs, is held by some other process that is also
waiting for some other resource to be released. None of the processes is progressing they are all
waiting. The computer becomes unresponsive since all the processes are blocked.
Example Scenario:
Assume three processes P1, P2, and P3 and three resources R1, R2, and R3:
Page 16 of 25
Operating System (CS1103)
P1 holds R1 and waits for R2.
P2 holds R2 and waits for R3.
P3 holds R3 and waits for R1.
Real-life Example:
Since each is waiting for the other, neither can proceed, leading to a deadlock.
Deadlock Operations
1. Request: The process asks for a resource. If unavailable, the process must wait.
2. Use: Once acquired, the process operates on the resource.
3. Release: The process frees the resource after use, allowing other processes to access it.
A deadlock can occur if all the following four Coffman conditions hold good:
1. Mutual Exclusion
o Definition: A resource cannot be used by more than one process simultaneously.
o Example:
Pen and paper are non-shareable resources.
Student A holds the pen, so Student B cannot use it.
Student B holds the paper, so Student A cannot use it.
2. Hold and Wait
o Definition: A process holds at least one resource while waiting to acquire
additional resources held by other processes.
o Example:
Student A holds the pen and waits for the paper.
Student B holds the paper and waits for the pen.
Neither releases their current resource until they acquire the missing one.
3. No Preemption
o Definition: Resources cannot be forcibly taken away from a process; they must be
released voluntarily.
o Example:
Student A cannot snatch the paper from Student B.
Student B cannot snatch the pen from Student A.
Page 17 of 25
Operating System (CS1103)
Resources (pen/paper) are only released when the student chooses to do
so.
4. Circular Wait
o Definition: A circular chain of processes exists where each process waits for a
resource held by the next process in the chain.
o Example:
Student A waits for Student B’s paper.
Student B waits for Student A’s pen.
This creates a cycle of dependencies, preventing both from proceeding.
1. Deadlock Ignorance
2. Deadlock Prevention
3. Deadlock Avoidance
4. Detection and Recovery
1. Deadlock Ignorance
2. Deadlock Prevention
To prevent deadlocks, the system ensures that at least one of the four necessary conditions never
holds good, i.e., at least one condition is false.
Some resources (e.g., read-only files) can be shared among multiple processes,
removing the need for mutual exclusion.
However, most resources (e.g., printers, CPU, memory) require mutual exclusion,
making this method impractical in many cases
Page 18 of 25
Operating System (CS1103)
A process must request all the required resources at once before execution begins.
If resources are not available, the process must wait. Or request only when
holding none.
This leads to low resource utilization and possible starvation.
3. Eliminating No Preemption
Page 19 of 25
Operating System (CS1103)
2. Deadlock Avoidance
Deadlock avoidance is a technique where the operating system dynamically analyzes resource
allocation to ensure that the system never enters a deadlocked state. Unlike deadlock
prevention, which restricts resource allocation upfront, avoidance allows more flexible
allocation but ensures that the system always remains in a safe state.
Safe State: A system is in a safe state if resources can be allocated without causing a
deadlock.
Unsafe State: If a system cannot allocate resources safely, it is in an unsafe state,
increasing the risk of deadlock. ie if resource allocation continues, a deadlock may occur.
Starvation: A condition where a process waits indefinitely for resources because other
processes are given priority.
Page 20 of 25
Operating System (CS1103)
1. Graph Components
Page 21 of 25
Operating System (CS1103)
Drawback of RAG:
Banker's Algorithm
Assuming there are n processes and m resource types, the following data structures are used:
1. Available: A vector of length m that indicates the number of available instances of each
resource.
o Available[j] = k means there are k instances of resource Rj available.
2. Max: An n x m matrix that defines the maximum demand of each process.
o Max[i, j] = k means process Pi may request at most k instances of Rj.
3. Allocation: An n x m matrix that shows the number of resources currently allocated to
each process.
o Allocation[i, j] = k means Pi currently holds k instances of Rj.
4. Need: An n x m matrix that represents the remaining resource need of each process.
o Need[i, j] = Max[i, j] – Allocation[i, j].
5. Finish: A Boolean vector of size n, initialized as false, indicating whether a process has
completed execution.
Page 22 of 25
Operating System (CS1103)
Page 23 of 25
Operating System (CS1103)
Deadlock Recovery
When a system enters a deadlock state, it must recover using various techniques. Deadlock
recovery can be classified into two main approaches:
When a deadlock occurs, the system can recover by taking back allocated resources from one
or more processes and reassigning them to break the deadlock.
Resource Preemption
2. Process Termination
When resource preemption and rollback are not sufficient, the OS may terminate one or more
processes to recover from deadlock.
Kill a Process
Page 24 of 25
Operating System (CS1103)
o Selecting the right process to kill.
o Ensuring the system remains stable after termination.
Page 25 of 25