OS Unit 2
OS Unit 2
• The operating system sees only a single process and will not schedule the
different threads of the process on separate processors.
• Consequently, there is no performance benefit associated with executing
multiple user-level threads on a multiprocessor system.
4. Name and draw five different process states with proper definition. (or) Draw
a diagram to show the different process states. (NOV/DEC 2024)
Process – A process is a program in execution
• New. The process is being created.
• Running. Instructions are being executed.
• Waiting. The process is waiting for some event to occur (such as an I/O
completion or reception of a signal).
• Ready. The process is waiting to be assigned to a processor.
• Terminated. The process has finished execution.
• The acquire()function acquires the lock, and the release() function releases the
lock.
6. “Priority inversion is a condition that occurs in real time systems where a
lower priority access is starved because higher priority processes have gained
hold of the CPU. “. Comment on this statement.(April/May 2024)
• Priority inversion is a problem that occurs in concurrent processes when low-
priority threads hold shared resources required by some high-priority threads,
causing the high priority-threads to block indefinitely.
• This problem is enlarged when the concurrent processes are in a real time
system where high- priority threads must be served on time.
• When a high-priority thread needs a resource engaged by a low-priority thread,
the low priority thread is preempted, the original resource is restored and the
high-priority thread is allowed to use the original resource.
9. Define a process.
A process is a program in execution. It is an active entity and it includes the
process stack, containing temporary data and the data section contains global
variables.
10. What is process control block?
Each process is represented in the OS by a process control block. It contains
many pieces of information associated with a specific process.
26. Write the four situations under which CPU scheduling decisions take
place.
CPU scheduling decisions may take place under the following four
circumstances:
1. When a process switches from the running state to the waiting state.
2. When a process switches from the running state to the ready state.
3. When a process switches from the waiting state to the ready state.
4. When a process terminates.
30. What is a deadlock? What is starvation? How do they differ from each
other? (April/May 2024)
• A deadlock is a situation where a number of processes cannot precede
without a resource that another holds, but cannot release any resources
that it is currently holding. A deadlock ensures that no processes can
proceed.
• Where as a starvation is a situation where a signal process is never given a
resource or event that it requires to proceed, this includes CPU time.
• They differ in that a deadlock ensures that no processes can proceed where
as starvation only a single process fails to proceed.
• Only one thread at a time can take the ownership of a mutex and apply
the lock.
• Once it done utilizing the resource and it may release the mutex lock.
PART B
1. Explain in detail about process concept. (or) Explain the seven-state model of
a process and also explain the queuing diagram for the same. Is it possible to have
more than one blocked queue, if so can a process reside in more than one queue?
(April/May 2024)
Process Concept
• Process is a program in execution. A process is the unit of work in a
modern time-sharing system.
• Even on a single-user system, a user maybe able to run several programs at
one time: a word processor, a Web browser, and an e-mail package.
• It also includes program counter, processor’s registers, stack, data section,
heap; Refer figure 1=2.1.
2. Describe the difference among short term, medium term and long term
scheduling with suitable example.
Process Scheduling
• The objective of multiprogramming is to have some process running
at all times, to maximize CPU utilization.
• The objective of time sharing is to switch the CPU among processes
so frequently that users can interact with each program while it is
running.
• To meet these objectives, the process scheduler selects an available
process (possibly from a set of several available processes) for
program execution on the CPU.
Scheduling Queues
• As processes enter the system, they are put into a job queue, which
consists of all processes in the system.
• The processes that are residing in main memory and are ready and
waiting to execute are kept on a list called the ready queue.
• The list of processes waiting for a particular I/O device is called a
device queue. Each device has its own device queue. Refer figure
2.4.
1. Shared-Memory Systems
• Inter Process Communication using shared memory requires
communicating processes to establish a region of shared memory.
• A producer process produces information that is consumed by a
consumer process.
• One solution to the producer–consumer problem uses shared memory.
• Two types of buffers can be used.
• The unbounded buffer places no practical limit on the size of the buffer.
• The bounded buffer assumes a fixed buffer size.
2. Message-Passing Systems
• Message passing provides a mechanism to allow processes to
communicate and to synchronize their actions without sharing the same
address space.
• A message-passing facility provides at least two operations:
• send(message)
• receive(message)
Here are several methods for send()/receive() operations:
• Naming
• Synchronization
• Buffering
1. Naming:
• Direct or indirect communication
• Synchronous or asynchronous communication
• Automatic or explicit buffering
Direct and Indirect Communication
In Direct Communication, Each process that wants to communicate must
explicitly name the recipient or sender of the communication.
In this scheme, the send() and receive() primitives are defined as:
• send(P, message)—Send a message to process P.
• receive(Q, message)—Receive a message from process Q.
A direct communication link in this scheme has the following properties:
• Symmetry communication - both the sender process and the receiver
process must name the other to communicate.
3. Economy.
• Allocating memory and resources for process creation is costly.
• Because threads share the resources of the process to which they
belong, it is more economical to create and context-switch threads.
4. Scalability.
• The benefits of multithreading can be even greater in a multiprocessor
architecture, where threads may be running in parallel on different
processing cores.
• A single-threaded process can run on only one processor, regardless
how many are available.
Types of Parallelism
• In general, there are two types of parallelism:
1. Data parallelism
2. Task parallelism.
• Data parallelism - The two threads would be running in parallel on
separate computing cores.
• Task parallelism - involves distributing not data but tasks (threads)
across multiple computing cores. Each thread is performing a unique
operation.
7. Explain in detail about multithreading models.
Multithreading Models
• Support for threads may be provided either at the user level, for user threads, or
by the kernel, for kernel threads.
• User threads are supported above the kernel and are managed without kernel
support, whereas kernel threads are supported and managed directly by the
operating system.
• Three common ways of establishing such are Relationship:
o many-to-one model
o one-to-one model
o many-to-many model
Many-to-One Model
• The many-to-one model maps many user-level threads to one kernel thread.
• Thread management is done by the thread library in user space, so it is efficient.
• However, the entire process will block if a thread makes a blocking system call.
• Many-to-one model allows the developer to create as many user threads, it does
not result in true concurrency, because the kernel can schedule only one thread
at a time. Refer figure 2.11.
One-to-One Model
• The one-to-one model maps each user thread to a kernel thread.
• It also allows multiple threads to run in parallel on multiprocessors.
• The only drawback to this model is that creating a user thread requires creating
the corresponding kernel thread.
• The one-to-one model allows greater concurrency, but the developer has to be
careful not to create too many threads within an application. Refer 2.12.
Threading issues:
• fork() and exec() system calls
• Thread cancellation
• Signal handling
• Thread pools
• Thread specific data
fork() and exec() system calls:
• A fork() system call may duplicate all threads or duplicate only the thread that
invoked fork().
• If a thread invoke exec() system call ,the program specified in the parameter to exec
will replace the entire process.
Thread cancellation:
• It is the task of terminating a thread before it has completed.
• A thread that is to be cancelled is called a target thread.
• There are two types of cancellation namely
1. Asynchronous Cancellation – One thread immediately terminates the target
thread.
2. Deferred Cancellation – The target thread can periodically check if it should
terminate, and does so in an orderly fashion.
Signal handling:
1. A signal is a used to notify a process that a particular event has
occurred.
2. A generated signal is delivered to the process.
• Deliver the signal to the thread to which the signal applies.
• Deliver the signal to every thread in the process.
10. Define Critical Section, critical resource. Explain the need for enforcing
mutual exclusion using echo function as an example in both uniprocessor
and multiprocessor environment. (April/May 2024)
Critical Section: A critical section is a part of a program that accesses
shared resources, such as memory, files, or variables, which must not be
accessed by more than one process or thread at a time to prevent race conditions.
Critical Resource: A critical resource is a resource that multiple processes or
threads need to access, but only one can use at a time to maintain data
consistency and avoid conflicts.
Need for Enforcing Mutual Exclusion
Mutual exclusion ensures that when one process is executing in its
critical section, no other process can enter its critical section simultaneously.
This is necessary to prevent data corruption, inconsistent states, and race
conditions.
Example: echo Function in Uniprocessor and Multiprocessor Environments
The echo command in Unix-based systems prints text to the terminal. If
multiple processes execute echo simultaneously, they may try to write to the
same output stream (e.g., the terminal), causing interleaved or corrupted output.
Uniprocessor Environment
• Since only one process executes at a time due to time-sharing, mutual
exclusion is enforced using software mechanisms like semaphores or
locks.
• Example issue: If two processes execute echo "Hello" concurrently, without
mutual exclusion, their outputs may mix (HHeelllooo instead of Hello).
• Solution: Implement a lock (e.g., a semaphore) that ensures only one
process executes echo at a time.
Multiprocessor Environment
• Multiple processors can execute different processes simultaneously,
increasing the risk of race conditions.
• Example issue: If two processes running on separate CPUs execute echo
"Hello" simultaneously, both may try to write to the terminal at the same
time, leading to mixed output.
12. Explain in detail about semaphores. Write the algorithm using test
and set instruction that satisfy all the critical section requirements.
A semaphore S is an integer variable that, apart from
initialization, is accessed only through two standard atomic operations:
wait() - operation was originally termed P (from the Dutch proberen,
“totest”);
signal() - was originally called V (from verhogen, “to increment”).
The definition of wait() is as follows:
wait(S)
{
while (S <= 0)
; // busy wait
S--;
}
The definition of signal() is as follows:
signal(S)
{
S++;
}
• All modifications to the integer value of the semaphore in the wait() and
signal() operations must be executed indivisibly.
• That is, when one process modifies the semaphore value, no other
process can simultaneously modify that same semaphore value.
Test and Set() instruction
booleanTestAndSet (boolean&target)
{
booleanrv = target;
target = true;
returnrv;
}
Swap
void Swap (boolean&a, boolean&b)
{
boolean temp = a;
a = b;
b = temp;
}
Semaphore Usage
• Operating systems often distinguish between counting and binary
semaphores.
• The value of a counting semaphore can range over an unrestricted
domain.
• The value of a binary semaphore can range only between 0 and 1.
• Thus, binary semaphores behave similarly to mutex locks.
• Counting semaphores can be used to control access to a given resource
consisting of a finite number of instances.
Semaphore Implementation
To implement semaphores under this definition, we define a semaphore as
follows:
type def struct
{
int value;
struct process *list;
} semaphore;
• When a process must wait on a semaphore, it is added to the list of
processes.
• A signal() operation removes one process from the list of waiting
processes and awakens that process.
The wait() semaphore operation can be defined as
wait(semaphore *S)
{
S->value--;
if (S->value < 0) {
add this process to S->list;
block();
}
}
The signal() semaphore operation can be defined as
signal(semaphore *S)
{
S->value++;
if (S->value <= 0) {
remove a process P from S->list;
wakeup(P);
}
}
• The block() operation suspends the process that invokes it.
• The wakeup(P) operation resumes the execution of a blocked process P.
2. Dining-Philosophers Problem:
• The Dining Philosopher Problem states that K philosophers seated
around a circular table with one chopstick between each pair of
philosophers as shown figure 2.15.
• There is one chopstick between each philosopher. A philosopher
may eat if he can pickup the two chopsticks adjacent to him.
• One chopstick may be picked up by any one of its adjacent
followers but not both. This problem involves the allocation of
limited resources to a group of processes in a deadlock-free and
starvation-free manner.
} while (true);
2. Readers and Writers Problem:
• Suppose that a database is to be shared among several concurrent
processes. Some of these processes may want only to read the
database, whereas others may want to update (that is, to read and
write) the database.
• We distinguish between these two types of processes by referring to
the former as readers and to the latter as writers.
• Precisely in OS we call this situation as the readers-writers
problem.
• Problem parameters:
o One set of data is shared among a number of processes.
o Once a writer is ready, it performs its write. Only one writer
may write at a time.
o If a process is writing, no other process can read it.
o If at least one reader is reading, no other process can write.
o Readers may not write and only read.
The structure of writer process
do {
wait(rw mutex);
...
/* writing is performed */
...
signal(rw mutex);
} while (true);
The structure of reader process
do {
wait(mutex);
read count++;
if (read count == 1)
wait(rw mutex);
signal(mutex);
...
/* reading is performed */
...
wait(mutex);
read count--;
if (read count == 0)
signal(rw mutex);
signal(mutex);
} while (true);
4. Sleeping Barber Problem:
• Barber shop with one barber, one barber chair and N chairs to wait in.
• When no customers the barber goes to sleep in barber chair and must
be woken when a customer comes in.
• When the CPU is free, it is allocated to the process at the head of the
queue.
• The running process is then removed from the queue.
Advantage: The code for FCFS scheduling is simple to write and understand.
Disadvantage: The average waiting time under the FCFS policy is often quite
long.
Consider the following set of processes that arrive at time 0, with the length of
the CPU burst given in milliseconds:
Process Burst Time
P1 24
P2 3
P3 3
If the processes arrive in the order P1, P2, P3, and are served in FCFS order,
Gantt chart
• Priority Scheduling
• Apriority is associated with each process, and the CPU is allocated to
the process with the highest priority.
• Equal-priority processes are scheduled in FCFS order.
• An SJF algorithm is simply a priority algorithm where the priority (p) is
the inverse of the (predicted) next CPU burst.
Consider the following set of processes, assumed to have arrived at time 0
in the order P1, P2, · · ·, P5, with the length of the CPU burst given in
milliseconds:
Process Burst Time Priority
P1 10 3
P2 1 1
P3 2 4
P4 1 5
P5 5 2
Gantt chart:
Let’s calculate the average waiting time for this schedule. P1 waits for 6
milliseconds (10 - 4), P2 waits for 4 milliseconds, and P3 waits for 7
milliseconds.
Thus, the average waiting time is 17/3 = 5.66 milliseconds.
19. What is a deadlock? What are the necessary conditions for a deadlock
to occur? (or) Explain deadlock detection with examples. (NOV/DEC
2024)
Deadlock Definition
• A process requests resources.
• If the resources are not available at that time, the process enters a wait
state.
• Waiting processes may never change state again because the resources
they have requested are held by other waiting processes. This situation
is called a deadlock.
Resources
• Request: If the request cannot be granted immediately then the requesting
process must wait until it can acquire the resource.
• Use: The process can operate on the resource
• Release: The process releases the resource.
Four Necessary conditions for a deadlock
Mutual exclusion:
• At least one resource must be held in a non sharable mode.
Process states
• Process P1 is holding an instance of resource type R2, and is waiting for
an instance of resource type R1 as shown in figure 2.22.
Resource Allocation Graph with a deadlock
F(diskdrive)=5,
F(Printer)=12.
• Each process can request resources only in an increasing order of
enumeration.
• When process Pi request resource Rj, the claim edge Pi ->Rj is converted
to a request edge.
• Similarly, when a resource Rj is released by Pi the assignment edge Rj ->
Pi is reconverted to a claim edge Pi ->Rj
• The request can be granted only if converting the request edge Pi ->Rj to
an assignment edge Rj -> Pi does not form a cycle.
• If no cycle exists, then the allocation of the resource will leave the
system in a safe state.
• If a cycle is found, then the allocation will put the system in an unsafe
state.
Banker's algorithm
o Safety Algorithm
o Resource request algorithm
Data structures used for bankers algorithm
• Available: indicates the number of available resources of each type.
• Max: Max[i, j]=k then process Pi may request at most k instances of
resource type Rj
• Allocation: Allocation[i. j]=k, then process Pi is currently allocated K
instances of resource type Rj
• Need: if Need[i, j]=k then process Pi may need K more instances of
resource type Rj
Need [i, j]=Max[i, j]-Allocation[i, j]
1. Safety algorithm
1. Initialize work := available and Finish [i]:=false for i=1,2,3 .. n
2. Find an i such that both
Finish[i]=false
a. Needi<= Work
i. if no such i exists, goto step 4
3. work :=work+ allocationi;
a. Finish[i]:=true
goto step 2
4. If finish[i]=true for all i, then the system is in a safe state
2. Resource Request Algorithm
Let Requesti be the request from process Pi for resources.
25. Consider the table given below for a system, find the need matrix
and the safety sequence, is the request from process P1(0, 1, 2) can be
granted immediately.
Resource – 3 types
A – (10 instances)
B – (5 instances)
C – (7 instances)
Step 5:
Safety for process P4
need4 = (4, 3, 1)
If need4 ≤ Available
If [(4, 3, 1) ≤ (6, 4, 3)]
P4 will execute.
Available = Available + Allocation
= (7, 4, 3) + (0, 0, 2)
= (7, 4, 5)
Step 6:
Safety for process P0
need0 = (7, 4, 3)
if need0 ≤ Available
if [(7, 4, 3) ≤ (7, 4, 5)]
P0 will execute.
Available = Available + Allocation
= (7, 4, 5) + (0, 1, 0)
= (7, 5, 5)
Step 7:
Safety for process P2
need2 = (6, 0, 0)
if need2 ≤ Available
if [(6, 0, 0) ≤ (7, 5, 5)]
P2 will execute.
Available = Available + Allocation
= (7, 5, 5) + (3, 0, 2)
= (10, 5, 7)
Safety Sequence = <P1, P3, P4, P0, P2>
28. Summarize the difference between user thread and kernel thread. (NOV/DEC
2024)
Feature User Thread Kernel Thread
Definition Managed by user-level Managed and scheduled
libraries, without direct by the operating system
OS involvement. kernel.
Performance Faster, as thread Slower, due to kernel
management (creation, involvement in scheduling
switching) is done in user and context switching.
space without kernel
intervention.
Scheduling Handled by the user-level Handled by the OS
thread library; the OS is scheduler, ensuring
unaware of user threads. system-wide fairness.
Blocking If one thread blocks (e.g., If a thread blocks, other
on I/O), all threads in that threads in the same
process may block. process can still execute.
Portability More portable, as they do Less portable, as they rely
not depend on the OS on specific OS
kernel. implementations.
Multiprocessing Support Cannot take full Can run on multiple CPUs
30. Explain the methods how deadlock can be avoided? Assume that there are
three resources, A,B, and C. There are 4 processes P0 to P3. At T0, the state of
the system is given below.
• For each process, subtract the allocated resources from the maximum needed
resources:
o Need(A) = Maximum(A) - Allocation(A)
o Need(B) = Maximum(B) - Allocation(B)
o Need(C) = Maximum(C) - Allocation(C)
2. Apply Banker's Algorithm:
• Available Resources: Let's assume the available resources at T0 are A=1, B=1, C=1.
• Check for Safe State:
o Step 1: Find a process that can be completely satisfied with the available
resources.
▪ P2 can be satisfied with its need (A=0, B=1, C=1) as it is fully covered by
the available resources.
▪ Update available resources: A=1, B=0, C=0.
o Step 2:
▪ P3 can be satisfied with its need (A=1, B=0, C=0) using the updated
available resources.
▪ Update available resources: A=0, B=0, C=0.
o Step 3:
▪ P0 can be satisfied with its need (A=1, B=1, C=1) using the updated
available resources.
▪ Update available resources: A=0, B=0, C=0.
o Step 4:
▪ P1 cannot be satisfied with its need (A=2, B=3, C=2) as there are no
available resources left.
• Conclusion: The system is in a safe state because a sequence of processes (P2, P3,
P0) can be executed without causing a deadlock, even if each process requests its
maximum need.
Deadlock Avoidance with Banker's Algorithm:
• Before allocating a resource to a process, check if the system would remain in a
safe state after allocation.
• If allocating a resource would result in an unsafe state, deny the request to prevent
potential deadlock.
31. Consider the execution of two processes P1 and P2 with the following CPU and
I/O burst times.
Each row shows the required resource for the process and the time that the
process needs that resource. For example "Net 3" in fourth row says that P2
needs network card for 3 time units.
(i) If P2 arrives 2 time units after P1 and the scheduling policy is non-
preemptive SJF then calculate the finish time for each process and the CPU idle
time in that duration. (7)
(ii) If P2 arrives 2 time units before P1 and the scheduling policy is preemptive
SJF then calculate the finish time for each process and the CPU idle time in
that duration. (8) (April/May 2024)
(i) Non-preemptive SJF with P2 arriving 2 time units after P1:
• Process execution order: P1 (CPU 3) -> P1 (Net 4) -> P1 (Disk 3) -> P1 (CPU 2) ->
P2 (CPU 4) -> P2 (Net 4) -> P2 (Disk 3) -> P2 (CPU 3) -> P2 (Net 3)
• Finish times:
o P1: 12 time units (3 CPU + 4 Net + 3 Disk + 2 CPU)
o P2: 18 time units (from the time P2 arrives at time unit 2: 4 CPU + 4 Net +
3 Disk + 3 CPU + 3 Net)
• CPU idle time: 2 time units (between when P1 finishes its first CPU burst and P2
arrives)
(ii) Preemptive SJF with P2 arriving 2 time units before P1:
• Process execution order:
P2 (CPU 4) -> P1 (CPU 3) -> P2 (Net 4) -> P1 (Net 4) -> P2 (Disk 3) -> P1 (Disk 3) -
> P2 (CPU 3) -> P1 (CPU 2) -> P2 (Net 3)
• Finish times:
• P1: 13 time units (3 CPU + 4 Net + 3 Disk + 2 CPU)
• If P0 is currently allocated (1, 0, 0) and P1 requests (0, 1, 0), P1 will be granted the
resource immediately.
• Now, if P2 requests (0, 0, 1), it will be blocked because the resource is not available.
• If P0 then requests (0, 1, 0), it will be granted the resource that was previously held
by P1 since P1 is no longer waiting for it.
• This scenario can repeat continuously, causing P2 to remain blocked indefinitely
waiting for the resource currently held by either P0 or P1.
(i) Predict whether deadlock occurs or not. If it occurs, give an example. If not,
which necessary condition cannot occur?
Deadlock Prediction
• Deadlock occurs when the system enters a state where a set of processes are
waiting for resources held by each other in a circular dependency, with no
process able to proceed.
• To analyze this, let’s check the four necessary conditions for deadlock:
1. Mutual Exclusion: Resources are allocated to one process at a time—this
condition holds.
2. Hold and Wait: Processes may hold some resources while requesting more—
this condition holds.
3. No Preemption: The system policy allows preemption, meaning resources can
be taken away from a blocked process and given to another process. This
violates the no preemption condition, preventing deadlock from occurring.
4. Circular Wait: Deadlock occurs when a circular chain of processes exists,
where each process is waiting for a resource held by the next in the chain.
However, since resources can be taken away, the chain is broken before
deadlock can occur.
Hence Deadlock does not occur because the no preemption condition is violated.