PROCESS
❖ Program in execution
( Word doc, ppt, game, python code)
❖ Into Windows task manager
Application Process Services user
No of pgms running List of process running
Process in Memory
Process State
❖ Current activity of the process
• New
• Ready
• Running
• Waiting
• Terminated
Process Control Block (PCB)
• Task control block
• Process details stored
- CPU scheduling information
(Priority, Burst time)
- Memory management information
(base register or limit register values)
- Accounting information
( how many CPU, how many jobs,
memory limit, how much CPU is used,
I/O device information)
- I/O status information
( information about I/O device
assigned to particular process, device
availability, which device is needed in
future)
Process Switching
Process Scheduling
❖ To maximize CPU utilization
❖ Process scheduler :
▪ Selects the process for execution among the available processes
▪ Maintains scheduling of processes with the help of scheduling queues
[
• Job queue : set of all process in the system
• Ready queue : set of all process ready and waiting to execute.
• Device queue : Set of all process waiting for I/O device.
Each device will have its own device queue.
Process will migrate among the queues
Queuing diagram
Ready and I/O Queue
Scheduler Types
❖ Short term scheduler or CPU scheduler
• Selects which process to be assigned to CPU for execution
• Invoked frequently (milliseconds)
• Must be Fast
Long term scheduler or job scheduler
• Selects which process is to be brought into ready queue
• Invoked infrequently (seconds , minutes)
• May be slow
• Controls the degree of multiprogramming
Processes can be described as either:
❖ I/O - bound process
• spends more time doing I/O than computation
• many short CPU burst
❖ CPU - bound process
• Spends more time doing computation
• Few very long CPU burst
Scheduler Types
❖ Medium term scheduler
• Used to decrease the degree of multiprogramming
• Performs swapping
Comparison among schedulers
S.N. Long-Term Scheduler Short-Term Scheduler Medium-Term Scheduler
It is a process swapping
1 It is a job scheduler It is a CPU scheduler
scheduler.
Speed is lesser than short Speed is fastest among Speed is in between both short
2
term scheduler other two and long term scheduler.
It provides lesser control
It controls the degree of It reduces the degree of
3 over degree of
multiprogramming multiprogramming.
multiprogramming
It is almost absent or minimal It is also minimal in time It is a part of Time sharing
4
in time sharing system sharing system systems.
It selects processes from pool It selects those processes It can re-introduce the process
5 and loads them into memory which are ready to into memory and execution can
for execution execute be continued.
Context Switching
❖ When CPU switches to another process , the system must save the
state of the old process and load the state for the new process
through context switching.
• overhead – System does no useful work while switching
• Dependent on hardware
Scheduling Criteria
• CPU Utilization : Average functioning time for which the processor is busy.
• Throughput : Number of process which can be executed in period of time.
• Waiting time : Average period of time for which the process spends waiting.
• Turnaround time : Time interval between the submission of process and the
completion of process.
• Response time : Time from the submission of a request to the first response
produced.
• Priority : Preference is given to process with higher priority
• Balanced utilization : Memory utilization , I/O devices and other system
resources are also considered other than CPU utilization for performance.
• Fairness : Avoid starvation by giving equal opportunity for the processes to
execute.
Scheduling Types
❖ Preemptive Scheduling : (with break)
• Running process replaced by higher priority process at any time
• More responsive
• Higher overhead due to process switching
❖ Non - Preemptive Scheduling : (without break)
• Once the CPU is allocated the process keeps the CPU until it releases the CPU due to
termination or switching to waiting state.
• Simple
• Used in Apple macintosh
Difference between preemptive and non-preemptive scheduling
S.No Preemptive Scheduling Non-Preemptive Scheduling
1 In preemptive scheduling, the bits of help or In non-preemptive scheduling, once the
resources are allotted to a procedure for a fixed bits of help or resources are allotted to a
time. procedure, the process carries it until it
satisfies or shifts to the waiting state.
2 Here, interruption can occur between the Here, the process cannot be interrupted.
processes.
3 It includes overheads of organising the It does not include overheads.
procedures.
4 It is adaptable in nature. It is not flexible in nature.
5 It is cost-oriented. Non-preemptive scheduling is not cost
oriented.
6 CPU utilization is high here. CPU utilization is low here.
Scheduling Algorithms
❖ First come First serve scheduling (FCFS)
• Process that requests the CPU first is allocated the CPU first
• It is non - preemptive
• Implemented using FIFO queue
Advantage:
• Very simple
• Easy to implement
Disadvantage:
Long average and worst case waiting time
Poor dynamic behaviour
❖ Shortest Job First Scheduling (SJFS)
• Process with the shortest burst time is scheduled first
• It can be preemptive or non-preemptive
Scheduling algorithms
Preemptive : If a new process arrives with CPU burst length less than remaining time of current
executing process, preemption takes place. This is know as Shortest Remaining Time First (SRTF).
Non-preemptive: Once CPU is given to the process it cannot be preempted until it completes its
CPU burst.
• If two process has the same CPU burst time, FCFS scheduling is used to break the tie.
• Used frequently in long term scheduling.
Advantage:
• It is optimal since it average waiting time of the process is less.
❖ Priority Scheduling
• CPU is allocated to the highest priority process
• Internally priorities are defined based on some measurable quantity
Time limit, Memory requirement, Number of open files, ratio of average I/O burst time to
average CPU burst time.
• External priority is set by the criteria external to OS
Importance of process, Type and amount of funds paid for computer use, department
sponsoring work etc
Scheduling Algorithms
• It can be preemptive or non-preemptive
Preemptive : CPU will be preempted when the newly arrived process has higher priority than currently running
process.
Non-preemptive: New process will be put at the head of the ready queue.
Disadvantage:
• Starvation or indefinite blocking: Low priority process waits indefinitely for CPU
• Aging: To overcome starvation aging is done ie priority of long waiting process is increased.
• Often process is switched from running to ready state in preemptive priority scheduling.
❖ Round Robin Scheduling (RR)
• Similar to FCFS
• It is preemptive
• Small unit of time : Time quantum or time slice is defined
• For a given time quantum scheduler goes around the ready queue allocating the CPU.
• Scheduler sets the timer to interrupt after the fixed time quantum is reached to dispatch the process.
Scheduling Algorithms
• Ready queue is a circular queue
• New process is added to the tail of the ready queue
• When the CPU burst time is less than the time quantum then CPU is released voluntarily.
• When the CPU burst time is greater than the time quantum then timer will go off and will cause an
interrupt to OS.
Disadvantages:
• Average waiting time is long
• Performance depends on time quantum
• If time slice is very large this algorithm acts as FCFS
• If time slice is very small, context switching increases.
Difference between FCFS and Round Robin scheduling
S.No. First Come First Served (FCFS) Round Robin(RR)
First Come First Served (FCFS) is the non- Round Robin(RR) is the preemptive scheduling
1.
preemptive scheduling algorithm. algorithm.
While RR has small overhead as it is necessary to record
2. FCFS has the minimal overhead. the time elapsed and then switch the process which
causes an overhead.
First Come First Served Scheduling
In Round Robin Scheduling Algorithm, for the short
3. Algorithm provides high response time for
processes there is very low response time.
the processes.
FCFS is inconvenient to use in the time It is mainly designed for the time sharing system and
3.
sharing system. hence convenient to use.
Average waiting time is generally not
In Round Robin Scheduling Algorithm average waiting
5. minimal in First Come First Served
time is minimal.
Scheduling Algorithm.
The process is simply processed in the order It is similar like FCFS in processing but uses time
6.
of their arrival in FCFS. quantum.
Scheduling Algorithms
❖ Multilevel Queue scheduling
CPU
• Ready queue is divided into number of separate queues
• Process is assigned to one queue based on some property
• Process cannot move from one queue to another
• Faces starvation
Scheduling Algorithms
❖ Multilevel Feedback Queue scheduling
• Ready queue is divided into number of separate queues
• Process using too much of CPU time will be moved to low priority queue
• Process can move from one queue to another
• overcomes starvation faced in multilevel queue scheduling
Scheduling Algorithms
❖ Parameters based on which Multilevel Feedback Queue scheduler is defined:
• Number of queues
• Scheduling algorithm for each queue
• Method used to determine which queue a process will enter when that process
needs service.
• Method used to determine when to demote a process to lower priority queue
• Method used to determine when to upgrade a process to higher priority queue
Difference between scheduling algorithms
Average
waiting time
Algorithm Allocation is Complexity (AWT) Preemption Starvation Performance
According to the
arrival time of the
Not complex Large. No No Slow performance
processes, the CPU is
FCFS allocated.
Based on the lowest
More complex Smaller than Minimum Average
CPU burst No Yes
than FCFS FCFS Waiting Time
SJF time (BT).
Depending
Same as SJF the
on some
allocation of the CPU
measures
is based on the More complex The preference is given
e.g., arrival Yes Yes
lowest CPU burst than FCFS to the short jobs
time,
time (BT). But it is
process size,
preemptive.
SRTF etc
Difference between scheduling algorithms
Average
waiting time
Algorithm Allocation is Complexity (AWT) Preemption Starvation Performance
According to the
Well performance but
Priority priority. The bigger This type is less Smaller than
Yes Yes contain a starvation
Pre- priority task complex FCFS
problem
emptive executes first
According to the
This type is less
Priority priority. with preemptive
complex than Most beneficial with
non- monitoring the new Smaller than No Yes
Priority batch systems
preemptive incoming FCFS
preemptive
higher priority jobs
Large as
According to the The
compared to
order of the process complexity Each process has given
SJF and No No
arrives with fixed depends on a fairly fixed time
Priority
time quantum (TQ) TQ size
RR scheduling.
Difference between scheduling algorithms
Average
waiting time
Algorithm Allocation is Complexity (AWT) Preemption Starvation Performance
More complex
According to the
than the Good performance but
process that resides Smaller than
priority No Yes contain a starvation
in the bigger queue FCFS
scheduling problem
priority
MLQ algorithms
It is the most Smaller than
According to the Complex but its all
process of a bigger complexity rate scheduling No No Good performance
priority queue. depends on the types in
MFLQ TQ size many cases
DEADLOCKS
❖ Definition: Deadlock is a condition in which two or more processes become
permanently blocked due to resource contention.
• Occurs in multiprogramming environment
• Process never finishes executing and system resources are tied up , preventing other jobs from starting.
❖ Resources ( memory space , I/O )
• R1, R2, R3 ………Rm
• Each resource Ri will have Wi instances ( instance can be single or multiple)
Ri
• Utilization of resource – Request , use and Release
❖ Resource allocation graph: ( directed graph used for describing deadlock )
• set of vertices (V) – holds 2 nodes
active process ( P = P1,P2,P3,…..Pn )
resource types ( R = R1,R2,R3,…..Rm)
• set of edges (E) – holds 2 edges
Request edge ( Pi → Rj )and assignment edge ( Rj → Pi )
DEADLOCKS
❖ Necessary Conditions for Deadlock to occur:
• Mutual Exclusion : A resource may be acquired exclusively by only one process at a time
ie non shareable.
• Hold and Wait : Requesting process holds a resource already and requests for another
resource
• No preemption : Once a process has obtained a resource, system cannot remove it from
process control until the process has completed using the resource.
• Circular wait : Each process in the list is waiting for a resource held by next process in
the list forming a circular list.
Deadlock
Deadlock
METHODS FOR HANDLING DEADLOCKS
• Use a protocol to prevent or avoid deadlock (ensuring that the system will never enter
deadlock state).
• Allowing the system to enter deadlock , then it is detected and recovered.
• Ignore the problem altogether and pretend that deadlock never occurs.
➢ Deadlock Prevention
➢ Deadlock Avoidance
➢ Deadlock Detection
➢ Deadlock Recovery
Deadlock prevention
❖ To ensure that deadlock never occurs :
• Deadlock prevention - set of method for ensuring that at least one of the necessary condition cannot hold
➢ Mutual exclusion
Holds for non sharable resource. Difficult to eliminate because certain resource like printer are non
shareable.
➢ Hold and wait
Prohibit a process from requesting another resource when it already holding a resource.
➢ No preemption
When the resource requested is not available to be allocated then the resource currently held is also released
and added into process request list.
➢ Circular wait
Imposes ordering of all resource types and sees to that the processes request resources in increasing order.
Deadlock Avoidance
❖ To ensure that deadlock never occurs :
• Deadlock avoidance – Requires that the OS be given in advance additional information
concerning which resource a process will request and use during its lifetime.
▪ To avoid deadlock system requires certain prior information:
• Each process must declare how much resource or maximum resource it requires
• Examines resource allocation state to ensure that there is no circular wait.
Resource allocation state is defined by :
- Number of available and allocated resource
- Maximum demand of process
Deadlock Avoidance
❖ To ensure that deadlock never occurs :
▪ Safe state
• Not deadlocked
• There is a scheduling order in which process can complete
▪ Unsafe state
• Not deadlocked
• No scheduling order
• OS cannot prevent process from requesting resource in such a way that deadlock occurs.
• Not all unsafe states are deadlocks. Unsafe state may lead to deadlock.
Bankers Algorithm ( Deadlock avoidance)
➢ It is applicable only when we have multiple instances
➢ Similar to banking system (bank will never allocate cash in such a way that it will no longer satisfy
the customer needs)
➢ Process must declare the resource required initially itself
➢ Less efficient than resource allocation graph system
➢ Data structure used in bankers algorithm
• n → number of process in system
• m → number of resource types
• Available
• Max
• Allocation
• Need
Data structure for Bankers Algorithm
Types of Bankers algorithm
• Safety algorithm
• Resource request algorithm
Safety algorithm
Safety Algorithm - Used to find if system is in safe state
Resource Request algorithm
Deadlock Detection
❖ Deadlock Detection
• Used only when there is deadlock
• Uses wait for graph ( extension of resource allocation graph) and Algorithm
➢ Wait for graph
• Can be used only for single instance resource
• Nodes are processes
• Edge Pi → Pj (Pi is blocked and waiting for Pj to release the resource)
• Smaller than the resource allocation graph
Deadlock Detection
• If there is a loop or cycle in wait for graph, there is deadlock.
➢ Algorithm:
• Used only for multiple instance resource
• Similar to Bankers algorithm
Deadlock Detection
❖ Detection algorithm is invoked based on two factors:
• How often is a deadlock likely to occur?
• How many process will be affected when deadlock happens?
Deadlock Recovery
❖ Detected deadlock is recovered using two methods:
➢ Process Termination
• All deadlocked processes are aborted
• process is aborted one by one by breaking the deadlock cycle.
• Selection of process for abortion is based on few parameters:
a) Priority of the process
b) How long the process has computed and how much time still it will take to
complete its task?
c) How many and what type of resource is used?
d) How many more resources process needs to complete?
➢ Resource Preemption
• Resource from deadlocked process is preempted and is given to other process
until deadlock cycle is broken.
Deadlock Recovery
• Three issues to be addressed
a) Selecting a victim:
• Select the process and the resource to be preempted
• Determine the order of preemption in order to minimize cost
b) Rollback:
• When we preempt the resource from a process, that process is rolled back to safe
state and is restarted after regaining old as well as new resource.
• If safe state not possible , total rollback is done ie process is aborted and
restarted from first.
c) Starvation:
• If a process does not get resource eventhough all resources are available then it
results in starvation.
• Same process must not be selected as victim
Process Synchronization
❖ Process may be independent or cooperating
▪ Independent process: It cannot affect or be affected by the execution of another process
▪ Cooperating process: It can affect or be affected by the execution of another process
(shared variable)
Reasons for cooperating process:
• Information sharing
• Computation speedup
• Modularity
• Convenience
❖ Process synchronization :
• Race condition: Cooperating process may access the shared data at the same
time or concurrently which will cause data inconsistency and will lead to race
condition. To overcome this problem process synchronization is used.
Producer Consumer problem
• Problem: Given the common fixed-size buffer, the task is to make sure that
the producer can’t add data into the buffer when it is full and the consumer
can’t remove data from an empty buffer.
• Solution: The producer is to either go to sleep or discard data if the buffer
is full. The next time the consumer removes an item from the buffer, it
notifies the producer, who starts to fill the buffer again. In the same
manner, the consumer can go to sleep if it finds the buffer to be empty. The
next time the producer puts data into the buffer, it wakes up the sleeping
consumer.
Process Synchronization
(Producer Consumer Problem)
Producer code Consumer code
Process Synchronization
(Critical Section Problem)
❖ Critical section
• Segment of code within a process
• Used to avoid race condition on data items
• In critical section process may change common variables, updates a table, writes a file etc
• At most only one process can execute in critical section
• Structure of process with critical section
Process Synchronization
(Critical Section Problem)
❖ Solution or conditions to be satisfied for Critical section problem:
➢ Mutual Exclusion
When one process is executing in critical session no other process is allowed to execute in
critical section.
➢ Progress
If no process is executing in critical section and at the sametime some processes wish to
enter critical section , processes that are not executing in remainder section can participate
in the decision on which will enter its critical section next.
➢ Bounded waiting
When a process requests access to critical section , a decision that grants it access may not
be delayed indefinitely. Bound must be fixed on number of times for a process to enter
critical section.
Mutex Locks
• Used to solve critical section problem
• Protects critical section using two operations:
- acquire() a lock
- release() the lock
• Calls to acquire() and release() must be atomic.
(no two process is allowed to acquire at the same time.
Made possible through hardware Implementation.)
• Also called spin lock since it requires busy
waiting. ie process is made to wait until available
becomes true.
Semaphores
• Provides more sophisticated way for process to synchronize their activity.
• Its an integer variable S
• Accessed using two functions:
- wait ()
- signal ()
• Types:
➢ Binary semaphore ( S value can be 0 or 1)
• Also known as mutex lock
• Tests binary condition
• It doesn’t guarantee bounded wait and there is starvation
➢ Counting semaphore or general semaphore
• Verifies range condition
• It guarantees bounded wait and there is no starvation
• semaphore variable accepts more than two values
• Two types : weak and strong semaphore
Weak: semaphore which does not specify the order in which processes are removed from queue
Strong: Process that has been blocked the longest is released from queue first
Semaphores implementation with no busy waiting
➢ With each semaphore there is an associated waiting queue
➢ Each entry in waiting queue has two data items:
• Value
• Pointer to next record in the list
➢ Two operations involved:
• Block – places the process invoking the operation on the appropriate waiting queue
• Wakeup – removes one of processes from waiting queue and places it in ready queue
typedef struct {
int value;
struct process *list;
} semaphore;
Semaphores
Code for wait () and signal ()
Classical problems of Synchronization
Used to test newly proposed synchronization schemes
➢ Bounded Buffer Problem or Producer Consumer problem
➢ Readers and Writers problem
➢ Dining Philosophers problem
Bounded Buffer Problem or Producer Consumer problem
Problem statement:
• Producer process must not add when buffer is full
• Consumer process must not consume when buffer is empty
Initialization:
n buffers – each can hold one item
Semaphore mutex = 1
Semaphore full = 0
Semaphore empty = n
• Eg: mutex = 1, full = 0 and empty = 4
Bounded Buffer Problem or Producer Consumer problem
Bounded Buffer Problem or Producer Consumer problem
➢ Solution to bounded buffer problem
• Producer must not overwrite a full buffer
• Consumer must not consume an empty buffer
• Producer and consumer must access buffers in a mutually exclusive manner
Reader Writer problem
➢ Problem statement:
• Allows multiple reader to read at the same time
• Only one single writer can access the shared data at the same time
➢ A data set is shared among the number of concurrent processes
• Reader: only reads the data set and don’t perform any write operation
• Writer: can both read and write
➢ Initialization
• Semaphore rw_mutex = 1 (decides whether to get into CS or not)
• Semaphore mutex = 1 (read count cant be modified by more than one reader. mutex takes
care of it)
• Integer read_count = 0 (indicates number of readers)
Reader Writer problem Variation
➢ First variation:
no reader kept waiting unless writer has permission to use shared object
➢ Second variation:
Once the writer is ready it performs writing as soon as possible Initialization
• Both reader and writer might have starvation leading to even more starvations
• Problem is solved on some systems by kernel providing reader-writer locks.
Dining Philosopher problem
• Philosophers will eat or think
• For eating both left and right chopsticks are required
• Philosophers don’t interact
• Shared data – noodles
Threads
• Unit of process
• Also called as Light weight process
• Each process holds multiple threads
• Each thread performs different operations (Eg: Word – spell check , alignment etc)
• Each thread can execute set of instruction
• Comprises of Thread id, Program counter, register set and a stack.
• Types:
Single thread - Process performs one task at a time
Multithread - Process performs more than one task at a time
- a thread shares with other thread its code section, data section and other OS
resources
Threads
Threads
• Classification of threads
➢ User level thread (many to one mapping thread)
• Created by user
• Thread management is done by user level thread libraries
• Code for creation and destroying thread, message passing and data transfer ,thread
scheduling is included into thread library.
• User level thread do not invoke Kernel for scheduling decision.
• Eg: POSIX P thread and Mach C thread
Advantage:
• These threads are fast to create and manage
• Thread switching does not require OS privilege
• These threads are portable
• User level threads works even if OS does not support threads
Disadvantage:
• If thread blocks , the kernel may block all threads
• Not suitable for multiprocessing system
Threads
➢ Kernel level thread
• Created by kernel
• Thread management is done by kernel
• Supported by OS.
• Threads are constructed and controlled by system calls.
• Eg: Windows , Sun Solaris
Advantage:
• Thread blocking in the kernel does not block all other threads in the same process
• Each thread can be treated separately
Disadvantage:
• Slower than the user level thread
• There will be overhead which will increase kernel complexity
Threads
Multithreading models
➢ Many to one model
• Many user level threads mapped to single kernel thread
• When one thread gets blocked all the threads will get blocked
• No parallel execution of threads is possible
• Few system currently uses this model
• Eg: Solaris green thread , GNU portable thread
Multithreading models
➢ One to one model
• Each user level thread maps to kernel thread
• When user thread is created it creates a kernel thread
• It has more concurrency than many to one
• Number of threads per process is sometimes
restricted due to overhead
• Eg: Windows, Linux
Multithreading models
➢ Many to many model
• Many user level threads is mapped to many kernel level threads
• Very efficient model since it is not necessary that for many user thread there has to be
equivalent kernel threads
• Allows OS to create sufficient number of kernel threads
• Eg: Windows with thread fiber package
Multithreading models
➢ Two level model
• Similar to many to many except it allows the user thread to be bound to kernel thread
• Eg: IRIX
Threading issues
➢ Semantics of FORK () and EXEC ()
➢ Signal handling
• Signal – used in UNIX to notify a process that an event has occurred
• Signal handler – used to process signals
• Types of signal handler – Default and user defined
Default – run by kernel in default when handling signal
User defined – overrides default
• Signal delivery incase of multithread
✓ Deliver the signal to the thread to which the signal applies
✓ Deliver the signal to the every thread in the process
✓ Deliver the signal to certain thread in the process
✓ Assign a specific thread to receive all signals related to the process
➢ Thread cancellation
➢ Thread local storage
➢ Scheduler activation
Threading issues
➢Thread cancellation
• Thread is terminated before it finishes
• Cancelled thread – Target thread
• Two approaches:
✓ Deferred cancellation
Allows the target thread to periodically check whether it has to be cancelled
✓ Asynchronous cancellation
Terminates the target thread immediately
• Request can only be raised for thread cancellation but actual cancellation depends on
thread state. (if state is disabled , thread cant be cancelled)
➢ Thread local storage
➢ Scheduler activation
Threading issues
➢ Thread local storage (TLS)
• Each thread has its own copy of data
• useful when there is no control over thread creation process
• Even when there is multiple function call TLS value will not change as it changes in local
variable
• TLS is unique to each thread
➢ Scheduler activation
• LWP – Light weight process
Virtual processor on which process can schedule user thread
to run.
• Upcall -if there is any error kernel will notify LWP through upcall
• Upcall handler – handles upcall
MONITOR
• Monitor type is ADT
• Used to overcome the drawbacks in semaphore
• Drawbacks in semaphore
➢ Order of wait(mutex) and signal(mutex) operation interchanged [multiple process will
enter CS]
signal(mutex);
critical section
wait(mutex);
➢ Instead of signal(mutex) again wait(mutex) is called. [Deadlock occurs]
wait(mutex);
critical section
wait(mutex);
➢ Either wait(mutex) or signal(mutex) is omitted. [Deadlock occurs]
MONITOR
• Function defined within monitor can access only those variables locally declared within
monitor and its formal parameters.
• Monitor construct ensures that only one process is active at a time within the monitor.
• Syntax:
MONITOR
Schematic view of monitor
MONITOR (Condition variable)
• Since synchronization scheme cannot be implemented directly condition variable is used.
• Condition variable: x,y
• Operations on condition variable:
➢ x.wait () – process that invokes this operation is suspended until x.signal () is invoked
➢ x.signal () – resumes the suspended process
• Monitor with condition variable
MONITOR (Condition variable choice)
• When process P invokes signal () then another process Q will be moved out from the
queue.
• Both P and Q cannot execute in parallel. Either P must wait or Q must wait.
➢ P to wait:
Signal and wait: P waits after calling signal function until Q leaves the monitor or waits for
another condition variable to call signal function.
➢ Q to wait:
Signal and continue: Q waits until P leaves the monitor or waits for another condition.
Solution for Dinning philosopher problem using monitor
• Monitor Imposes a restriction that a philosopher will pick up chopstick only when both chopsticks are
available.
• Three states are considered in the code (Thinking , Hungry and eating)
Resuming process within monitor
• When process P invokes signal () then another process Q will be moved out from the
queue.
• Both P and Q cannot execute in parallel. Either P must wait or Q must wait.
➢ P to wait:
Signal and wait: P waits after calling signal function until Q leaves the monitor or waits for
another condition variable to call signal function.
➢ Q to wait:
Signal and continue: Q waits until P leaves the monitor or waits for another condition.
Operation on process (creation and termination)
➢ Process Creation
❖ OS creates the process in following situation:
• Starting of new batch job
• User request for creating new process
• To provide new services by OS
• System call from currently running process
❖ Creating process – parent process
Created process – child process
• Both parent and child process have their own and private memory
• Parent process executes concurrently with child process
• Parent process waits until all its children terminates
❖ Process identification : PID – unique process identifier (integer value)
❖In UNIX – Process is created using fork() system call
Operation on process (creation and termination)
➢ Process Termination
• Process terminates after finishing its normal execution
• After termination OS deletes the process using exit() system call
• OS passes child's exit status to parent process and then discards the process. At the
sametime deallocates all the resources held by this process.
• Reasons for process termination:
o Normal completion of operation
o Memory is not available
o Time slice expired
o Parent termination
o Failure of I/O
o Request from parent process
o Misuse of access rights
Interprocess Communication (IPC)
• Cooperating Process needs IPC
• Two models of IPC:
➢ Message passing
➢ Shared memory
Interprocess Communication (IPC)
➢ If process P and Q wants to communicate
• Link has to be established to send and receive messages
• Implementation issues:
o How to establish link?
o Can a link be associated with more than two processes?
o How many links can be established between communicating processes?
o What is the capacity of the link?
o Is the size of the message sent through link fixed or variable?
o Is the link unidirectional or bidirectional?
Interprocess Communication (IPC)
(Types of Message passing)
➢ Direct Communication ( directly messages are sent)
• P sending message to Q
Send( Q, message)
• Q receiving message from P
receive( P, message)
• Properties of communication link
o Links are established automatically
o Link associated with one pair of communicating process
o Can a link be associated with more than two processes?
o There exists one link between each pair.
o link is usually bidirectional and may be unidirectional.
Interprocess Communication (IPC)
➢ Indirect Communication ( message sending is through mailbox)
• Each mailbox has unique id
• P and Q can communicate only through shared mailbox
• Properties of communication link
o Links are established only if there is a shared mailbox
o Link may be associated with many processes.
o Can a link be associated with more than two processes?
o There may exists many links between each pair.
o link may be unidirectional or bidirectional .
• Problem in mailbox sharing and solution
When P1 , P2 and P3 shares common mailbox
P1 sends msg to mailbox then P2 will receive or P3 will receive
Interprocess Communication (IPC)
• Solution
o Link may be associated with at most two processes alone.
o Allow only one process to execute receive operation
o Allow the system to select the receiver arbitrarily. Sender will be notified.
Interprocess Communication (IPC)
➢ Synchronization ( Blocking or Non blocking)
• Synchronous or Blocking
• Blocking send - Sender is blocked until the message is received
• Blocking receive - receiver is blocked until a message is available
• Asynchronous or Non Blocking
• Non Blocking send - Sender sends the message and continues
• Non Blocking receive - receiver receives
A valid message or null message
Interprocess Communication (IPC)
➢ Buffering
• Queue of messages attached to the link
• Implemented in three ways
o Zero capacity
• no messages are queued on the link
• Sender must wait for the receiver
o Bounded capacity
• finite length of ‘n’ messages
• Sender must wait if link is full
o Unbounded capacity
• infinite length of ‘n’ messages
• Sender never waits