UNIT II
PROCESS MANAGEMENT
Processes: Concept – Scheduling - Operations on
Processes - Interprocess Communication -Communication in
Client-Server Systems. Process Scheduling-Scheduling
Criteria – Scheduling Algorithms - Multiple-Processor
Scheduling.
Process Concept
Process Concept
Process – a program in execution.
Batch system – 1 job
Time-shared systems – multiple processes
Program – passive entity, process – active entity
Same program – multiple process
A process includes:
Text section – program code
program counter - address of next instruction to be
executed
Stack – temporary data (parameters, return address, local
variables, etc..,)
data section (global variables)
Process State
As a process executes, it changes state
new: The process is being created.
running: Instructions are being executed.
waiting: The process is waiting for some event to occur.
ready: The process is waiting to be assigned to a process.
terminated: The process has finished execution.
Diagram of Process State
Process Control Block (PCB)
Process Control Block (PCB)
Information associated with each process.
Pointer – points to next PCB in queue
Process state – new, ready, running, waiting, terminated
Program counter – addr of next instruction to be exec.
CPU registers – accumulators, index registers, stack
pointers, general purpose registers.
CPU scheduling information – priority, pointer to
scheduling queue, scheduling parameters, etc.,
Memory-management information – base, limit register
values, page table, segment table, etc.,
Accounting information – CPU time used, time limit,
process no., etc.,
I/O status information – I/O devices allocated, files
opened, etc.,
CPU Switch From Process to Process
Process Scheduling
Process Scheduling Queues
Job queue – set of all processes in the system.
Ready queue – set of all processes residing in main
memory, ready and waiting to execute.
Device queues – set of processes waiting for an I/O
device.
Process migration between the various queues.
Ready Queue And Various I/O Device Queues
Representation of Process Scheduling
Schedulers
Long-term scheduler (or job scheduler) - selects which
processes should be brought into the ready queue.
Short-term scheduler (or CPU scheduler) – selects which
process should be executed next and allocates CPU.
Addition of Medium Term Scheduling
Schedulers (Cont.)
Short-term scheduler is invoked very frequently
(milliseconds) (must be fast).
Long-term scheduler is invoked very infrequently
(seconds, minutes) (may be slow).
The long-term scheduler controls the degree of
multiprogramming, maintains process mix.
Processes can be described as either:
I/O-bound process – spends more time doing I/O than
computations, many short CPU bursts.
CPU-bound process – spends more time doing
computations; few very long CPU bursts.
Context Switch
When CPU switches to another process, the system must
save the state of the old process and load the saved state
for the new process.
Context-switch time is overhead; the system does no
useful work while switching.
Time dependent on hardware support.
Operations on Processes
Process Creation
Parent process create children processes, which, in turn
create other processes, forming a tree of processes (refer
fig.)
Resource sharing
Parent and children share all resources.
Children share subset of parent‟s resources.
Parent and child share no resources.
Execution
Parent and children execute concurrently.
Parent waits until children terminate.
Process Creation (Cont.)
Address space
Child duplicate of parent.
Child has a program loaded into it.
UNIX examples
fork system call creates new process
Processes Tree on a UNIX System
fork system call
Process Termination
Process executes last statement and asks the operating
system to delete it (exit).
Output data from child to parent (via wait).
Process‟ resources are deallocated by operating system.
Parent may terminate execution of children processes
(abort).
Child has exceeded allocated resources.
Task assigned to child is no longer required.
Parent is exiting.
Operating system does not allow child to continue if its
parent terminates.
Cascading termination.
Cooperating Processes
Cooperating Processes
Independent process cannot affect or be affected by the
execution of another process.
Cooperating process can affect or be affected by the
execution of another process
Advantages of process cooperation
Information sharing
Computation speed-up
Modularity
Convenience
Producer-Consumer Problem
Paradigm for cooperating processes, producer process
produces information that is consumed by a consumer
process.
unbounded-buffer places no practical limit on the size of the
buffer.
bounded-buffer assumes that there is a fixed buffer size.
Bounded-Buffer – Shared-Memory Solution
Shared data
#define BUFFER_SIZE 10
Typedef struct {
. . .
} item;
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
Solution is correct, but can only use BUFFER_SIZE-1
elements
Bounded-Buffer – Producer Process
item nextProduced;
while (1) {
while (((in + 1) % BUFFER_SIZE) == out)
; /* do nothing */
buffer[in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
}
Bounded-Buffer – Consumer Process
item nextConsumed;
while (1) {
while (in == out)
; /* do nothing */
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
}
Interprocess Communication (IPC)
Interprocess Communication (IPC)
Mechanism for processes to communicate and to
synchronize their actions.
Message Passing system – processes communicate with
each other without resorting to shared data.
Useful in distributed environment.
IPC facility provides two operations:
send(message) – message size fixed or variable
receive(message)
If P and Q wish to communicate, they need to:
establish a communication link between them
exchange messages via send/receive
Direct Communication
Processes must name each other explicitly:
send (P, message) – send a message to process P
receive(Q, message) – receive a message from process Q
Properties of communication link
Links are established automatically.
A link is associated with exactly one pair of communicating
processes.
Between each pair there exists exactly one link.
The link may be unidirectional, but is usually bi-directional.
Direct Communication
Processes must name each other explicitly (Symmetric):
send (P, message) – send a message to process P
receive(Q, message) – receive a message from process Q
Sender Processes must name Receiver explicitly:
send (P, message) – send a message to process P
Receive(id, message) – receive a message from any
process. Later, process from which message was received
is stored in „id‟.
Limitations:
Changing name of process => rename all references
Indirect Communication
Messages are directed and received from mailboxes (also
referred to as ports).
Mailbox – object in which messages are placed and
removed by processes
Each mailbox has a unique id.
Processes can communicate only if they share a mailbox.
Properties of communication link
Link established only if processes share a common mailbox
A link may be associated with many processes.
Each pair of processes may share several communication
links.
Link may be unidirectional or bi-directional.
Indirect Communication
Mailbox owned by
Process (mailbox in its own address space)
OS
Operations for mailbox in OS
create a new mailbox
send and receive messages through mailbox
destroy a mailbox
Primitives are defined as:
send(A, message) – send a message to mailbox A
receive(A, message) – receive a message from mailbox A
Indirect Communication
Mailbox sharing
P1, P2, and P3 share mailbox A.
P1, sends; P2 and P3 receive.
Who gets the message?
Solutions
Allow a link to be associated with at most two processes.
Allow only one process at a time to execute a receive
operation.
Allow the system to select arbitrarily the receiver. Sender is
notified who the receiver was.
Synchronization
Message passing may be either blocking or non-blocking.
Blocking is considered synchronous
Non-blocking is considered asynchronous
send and receive primitives may be either blocking or
non-blocking.
Blocking-send: sender blocked until msg sent
Non-Blocking-send: sender sends and resumes process
Blocking-receive: receiver waits until a msg is received
Non-Blocking-receive: receiver receives msg or resumes
process
Buffering
Queue of messages attached to the link; implemented in
one of three ways.
1. Zero capacity – 0 messages
Sender must wait for receiver .
2. Bounded capacity – finite length of n messages
Sender must wait if link full.
3. Unbounded capacity – infinite length
Sender never waits.
Communication in Client-Server Systems
Client-Server Communication
Sockets
Remote Procedure Calls
Remote Method Invocation (Java)
Sockets
A socket is defined as an endpoint for communication.
Concatenation of IP address and port
The socket 161.25.19.8:1625 refers to port 1625 on host
161.25.19.8
Communication consists between a pair of sockets.
Socket Communication
Sockets – Example programTCP - Server
import java.io.*;
import java.net.*;
public class server {
public static void main(String[] args) throws IOException
{
ServerSocket listener = new ServerSocket(2000);
try {
while (true) {
Socket socket = listener.accept();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out =new PrintWriter(socket.getOutputStream(), true);
out.println("Hello, client");
String input = in.readLine();
System.out.println(input);
}
finally {socket.close(); }
}
}
finally { listener.close(); }
}
}
Sockets – Example programTCP – Client
import java.io.*;
import java.net.*;
public class client
{
public static void main(String[] args) throws IOException
{
Socket socket = new Socket("localhost", 2000);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String input = in.readLine();
System.out.println(input);
out.println("Hello, server");
}
}
Sockets – Example programUDP – Server
import java.net.*;
import java.io.*;
public class UDPEchoServer
{
public static void main(String args[]) throws SocketException, IOException
{
DatagramSocket aSocket = new DatagramSocket(2000);
try
{
byte[] buffer = new byte[1000];
while(true)
{
DatagramPacket request = new DatagramPacket(buffer,buffer.length);
aSocket.receive(request);
DatagramPacket reply = new
DatagramPacket(request.getData(),request.getLength(),request.getAddress(),request.getPort());
aSocket.send(reply);
}
}
finally { aSocket.close(); }
}
}
Sockets – Example programUDP- Client
import java.net.*;
import java.io.*;
public class UDPEchoClient
{
public static void main(String args[]) throws SocketException, IOException
{
DatagramSocket aSocket = new DatagramSocket();
try
{
String m = "Hello UDPEchoServer";
InetAddress aHost = InetAddress.getLocalHost();
DatagramPacket request = new DatagramPacket(m.getBytes(), m.length(), aHost,
2000);
aSocket.send(request);
byte[] buffer = new byte[1000];
DatagramPacket reply = new DatagramPacket(buffer, buffer.length);
aSocket.receive(reply);
System.out.println("Reply: " + new String(reply.getData()).trim());
}
finally { aSocket.close(); }
}
}
Remote Procedure Calls
Remote procedure call (RPC) abstracts procedure calls
between processes on networked systems.
Stubs – client-side proxy for the actual procedure on the
server.
The client-side stub locates the server and marshalls the
parameters.
The server-side stub receives this message, unpacks the
marshalled parameters, and peforms the procedure on
the server.
Execution of RPC
Remote Method Invocation
Remote Method Invocation (RMI) is a Java mechanism
similar to RPCs.
RMI allows a Java program on one machine to invoke a
method on a remote object.
Marshalling Parameters
WORKING OF RMI
CLIENT VIRTUAL
MACHINE
REGISTRY VIRTUAL
MACHINE
SERVER VIRTUAL
MACHINE
CLIENT
SERVER
STUB
REMOTE
OBJECT
NAME,REF
REMOTE
OBJECT
SKELETON
76
5
43
2
1
2. Server registers
remote object
4. Registry returns
remote reference &
stub
5. Client invokes stub
1. Server creates
remote object
3. Client requests
object from registry
6. Stub talks to skeleton7. Skeleton invokes
remote object method
RMI – Example programAdd.java
import java.rmi.*;
public interface Add extends Remote
{
public int getSum() throws RemoteException;
}
RMI – Example programAddImpl.java
import java.rmi.*;
import java.rmi.server.UnicastRemoteObject;
public class AddImpl extends UnicastRemoteObject implements Add
{
public AddImpl() throws RemoteException
{
super();
}
public int getSum() throws RemoteException
{
System.out.println("Calculating the sum..");
int a=10;
int b=15;
int sum;
sum=a+b;
return sum;
}
}
RMI – Example programAddServer.java
import java.net.*;
import java.rmi.*;
public class AddServer
{
public static void main(String[] args)
{
try
{
AddImpl f = new AddImpl();
Naming.rebind("add", f);
System.out.println("Addition Server ready.");
}
catch (RemoteException rex)
{
System.out.println("Exception in AddImpl.main: " + rex);
}
catch (MalformedURLException ex)
{
System.out.println("MalformedURLException " + ex);
}
}
}
RMI – Example programAddClient
import java.rmi.*;
import java.net.*;
public class AddClient
{
public static void main(String args[])
{
try
{
Object o = Naming.lookup("add");
Add calculator = (Add) o;
int f = calculator.getSum();
System.out.println("The sum is: "+f);
}
catch (NotBoundException ex) {
System.err.println("Could not find the requested remote object on the server");
}
catch (RemoteException ex) {
System.err.println("Could not find the requested remote object on the server");
}
catch (MalformedURLException ex) {
System.err.println("Could not find the requested remote object on the server");
}
}
}
CPU Scheduling - Basic Concepts
CPU–I/O Burst Cycle
Process execution consists of a cycle of CPU execution
and I/O wait.
CPU burst distribution helps to choose CPU scheduling
algorithm
CPU And I/O Bursts (Alternating Sequence)
CPU-burst Times (Histogram)
CPU Scheduler
Selects from among the processes in memory that are
ready to execute, and allocates the CPU to one of them.
CPU scheduling decisions may take place when a
process:
1. Switches from running to waiting state.
2. Switches from running to ready state.
3. Switches from waiting to ready.
4. Terminates.
Scheduling under 1 and 4 is nonpreemptive (i.e. process
forced to release CPU).
All other scheduling is preemptive (i.e. process releases
CPU voluntarily).
Dispatcher
Dispatcher module gives control of the CPU to the
process selected by the short-term scheduler; this
involves:
switching context
switching to user mode
Dispatch latency – time it takes for the dispatcher to stop
one process and start another running.
Scheduling Criteria
Scheduling Criteria
CPU utilization – keep the CPU as busy as possible
Throughput – No. of processes that complete their
execution per time unit
Turnaround time – amount of time to execute a
particular process i.e. from the time submitted till the time
of completion (JobQ + ReadyQ + CPUburst + DeviceQ +
IOburst)
Waiting time – amount of time a process has been
waiting in the ready queue
Response time – amount of time it takes from when a
request was submitted until the first response is produced
i.e. 1st Waiting Time.
Optimization Criteria
Max CPU utilization
Max throughput
Min turnaround time
Min waiting time
Min response time
Scheduling Algorithms
First-Come, First-Served (FCFS) Scheduling
Process Burst Time
P1 24
P2 3
P3 3
Suppose that the processes arrive in the order: P1 , P2 , P3
The Gantt Chart for the schedule is:
Waiting time for P1 = 0; P2 = 24; P3 = 27
Average waiting time: (0 + 24 + 27)/3 = 17
P1 P2 P3
24 27 300
FCFS Scheduling (Cont.)
Suppose that the processes arrive in the order
P2 , P3 , P1 .
The Gantt chart for the schedule is:
Waiting time for P1 = 6; P2 = 0; P3 = 3
Average waiting time: (6 + 0 + 3)/3 = 3
Much better than previous case.
Convoy effect - short process behind long process i.e.
other processes wait for one big process to get off CPU.
P1P3P2
63 300
Shortest-Job-First (SJF) Scheduling
Associate with each process the length of its next CPU
burst. Use these lengths to schedule the process with the
shortest time.
Two schemes:
nonpreemptive – once CPU given to the process it cannot
be preempted until completes its CPU burst.
preemptive – if a new process arrives with CPU burst length
less than remaining time of current executing process,
preempt. This scheme is know as the
Shortest-Remaining-Time-First (SRTF).
SJF is optimal – gives minimum average waiting time for
a given set of processes.
Process Arrival Time Burst Time
P1 0.0 7
P2 2.0 6
P3 4.0 1
P4 5.0 4
SJF (non-preemptive)
Average waiting time = (0 + 10 + 3 + 3)/4 = 4
Example of Non-Preemptive SJF
P1 P3 P4
73 180
P2
8 12
Example of Preemptive SJF
Process Arrival Time Burst Time
P1 0.0 7
P2 2.0 4
P3 4.0 1
P4 5.0 4
SJF (preemptive)
Average waiting time = (9 + 1 + 0 +2)/4 = 3
P1 P3P2
42 110
P4
5 7
P2 P1
16
Determining Length of Next CPU Burst
Can only estimate the length.
Can be done by using the length of previous CPU bursts,
using exponential averaging.
Priority Scheduling
A priority number (integer) is associated with each
process
The CPU is allocated to the process with the highest
priority (smallest integer highest priority).
Preemptive
nonpreemptive
SJF is a priority scheduling where priority is the predicted
next CPU burst time.
Problem Starvation – low priority processes may never
execute.
Solution Aging – as time progresses increase the
priority of the process.
Process Arrival Time Burst Time Priority
P1 0.0 7 3
P2 2.0 4 4
P3 4.0 1 1
P4 5.0 4 2
Priority (non-preemptive)
Average waiting time = (0 + 10 + 3 + 3)/4 = 4
Example of Non-Preemptive Priority
Scheduling
P1 P3 P4
73 180
P2
8 12
Example of Preemptive Priority
Scheduling
Process Arrival Time Burst Time Priority
P1 0.0 7 4
P2 2.0 4 2
P3 4.0 1 1
P4 5.0 4 3
Priority (preemptive)
Average waiting time = (9 + 1 + 0 +2)/4 = 3
P1 P3P2
42 110
P4
5 7
P2 P1
16
Round Robin (RR)
Each process gets a small unit of CPU time (time
quantum), usually 10-100 milliseconds. After this time
has elapsed, the process is preempted and added to the
end of the ready queue.
If there are n processes in the ready queue and the time
quantum is q, then each process gets 1/n of the CPU time
in chunks of at most q time units at once. No process
waits more than (n-1)q time units.
Performance
q large FIFO
q small q must be large with respect to context switch,
otherwise overhead is too high.
Example of RR with Time Quantum = 20
Process Burst Time
P1 53
P2 17
P3 68
P4 24
The Gantt chart is:
Typically, higher average turnaround than SJF, but better
response.
P1 P2 P3 P4 P1 P3 P4 P1 P3 P3
0 20 37 57 77 97 117 121 134 154 162
Time Quantum and Context Switch Time
Multilevel Queue
Ready queue is partitioned into separate queues
Each queue has its own internal scheduling algorithm,
RR, FCFS, etc.,
Each queue is again scheduled using a scheduling
algorithm
Low scheduling overhead but inflexible.
Multilevel Queue Scheduling
Multilevel Feedback Queue
A process can move between the various queues; aging
can be implemented this way.
Multilevel-feedback-queue scheduler defined by the
following parameters:
number of queues
scheduling algorithms for each queue
method used to determine when to upgrade a process
method used to determine when to demote a process
method used to determine which queue a process will enter
when that process needs service
Example of Multilevel Feedback Queue
Three queues:
Q0 – time quantum 8 milliseconds
Q1 – time quantum 16 milliseconds
Q2 – FCFS
Scheduling
The scheduler first executes all processes in queue 0.
Only when queue 0 is empty will it execute processes in
queue 1.
Similarly, processes in queue 2 will be executed only if
queues 0 and 1 are empty.
A process that arrives for queue 1 will preempt a process in
queue 2.
A process that arrives for queue 0 will, in turn, preempt a
process in queue 1.
Example of Multilevel Feedback Queue
Scheduling
A process entering the ready queue is put in queue 0. A
process in queue 0 is given a time quantum of 8
milliseconds. If it does not finish within this time, it is moved
to the tail of queue 1.
If queue 0 is empty, the process at the head of queue 1 is
given a quantum of 16 milliseconds. If it does not complete,
it is preempted and is put into queue 2.
Processes in queue 2 are run on an FCFS basis, only when
queues 0 and 1 are empty.
Multilevel Feedback Queues
Multiple-Processor Scheduling
Multiple-Processor Scheduling
CPU scheduling is more complex when multiple CPUs
are available.
Let us assume Homogeneous processors within a
multiprocessor.
2 approaches:
Separate ready queue for each processor: Drawback is that,
some processor might be idle if its ready queue alone is
empty.
Common ready queue for all processor:
Approach 1: Each processor choose its own process.
Drawback is that, 2 processor could choose the same
process.
Approach 2 (Master-Slave): Master assigns, slave
executes.
Syllabus
UNIT II
PROCESS MANAGEMENT
Synchronization: The Critical-Section Problem -
Semaphores – Classic Problems of Synchronization.
The Critical-Section Problem
Background
Concurrent access to shared data may result in data
inconsistency.
Maintaining data consistency requires mechanisms to
ensure the orderly execution of cooperating processes.
Suppose that we modify the producer-consumer code by
adding a variable counter, initialized to 0 and incremented
each time a new item is added to the buffer
Bounded-Buffer
Shared data
#define BUFFER_SIZE 10
typedef struct {
. . .
} item;
item buffer[BUFFER_SIZE];
int in = 0;
int out = 0;
int counter = 0;
Bounded-Buffer
Producer process
item nextProduced;
while (1) {
while (counter == BUFFER_SIZE)
; /* do nothing */
buffer[in] = nextProduced;
in = (in + 1) % BUFFER_SIZE;
counter++;
}
Bounded-Buffer
Consumer process
item nextConsumed;
while (1) {
while (counter == 0)
; /* do nothing */
nextConsumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
}
Bounded Buffer
The statements
counter++;
counter--;
must be performed atomically.
Atomic operation means an operation that completes in
its entirety without interruption.
Bounded Buffer
The statement “count++” may be implemented in
machine language as:
register1 = counter
register1 = register1 + 1
counter = register1
The statement “count—” may be implemented as:
register2 = counter
register2 = register2 – 1
counter = register2
Bounded Buffer
If both the producer and consumer attempt to update the
buffer concurrently, the assembly language statements
may get interleaved.
Interleaving depends upon how the producer and
consumer processes are scheduled.
Bounded Buffer
Assume counter is initially 5. One interleaving of
statements is:
producer: register1 = counter (register1 = 5)
producer: register1 = register1 + 1 (register1 = 6)
consumer: register2 = counter (register2 = 5)
consumer: register2 = register2 – 1 (register2 = 4)
producer: counter = register1 (counter = 6)
consumer: counter = register2 (counter = 4)
The value of count may be either 4 or 6, where the
correct result should be 5.
Race Condition
Race condition: The situation where several processes
access – and manipulate shared data concurrently. The
final value of the shared data depends upon which
process finishes last.
To prevent race conditions, concurrent processes must
be synchronized.
Definitions
Process Synchronization:
Orderly execution of co-operating processes to maintain
consistency
Race Condition:
Several processes access and manipulate the same data
concurrently and the outcome of the execution depends on the
particular order in which the access takes place, is called a race
condition.
The Critical-Section
Consider a system consisting of n processes {Po,P1, ...,
P,-1).
Each process has a segment of code, called a critical
section, in which the process may be changing common
variables, updating a table, writing a file, and so on.
The critical-section problem is to design a protocol that
the processes can use to cooperate.
Each process must request permission to enter its critical
section. The section of code implementing this request is
the entry section.
The critical section may be followed by an exit section.
The remaining code is the remainder section.
The Critical-Section Problem
n processes all competing to use some shared data
Each process has a code segment, called critical section,
in which the shared data is accessed.
Problem – ensure that when one process is executing in
its critical section, no other process is allowed to execute
in its critical section.
Solution to Critical-Section Problem
1. Mutual Exclusion. If process Pi is executing in its critical
section, then no other processes can be executing in their
critical sections.
2. Progress. f no process is executing in its critical section
and some processes wish to enter their critical sections,
then only those processes that are not executing in their
remainder section can participate in the decision on
which will enter its critical section next, and this selection
cannot be postponed indefinitely.
3. Bounded Waiting. A bound must exist on the number of
times that other processes are allowed to enter their
critical sections after a process has made a request to
enter its critical section and before that request is
granted.
Initial Attempts to Solve Problem
Only 2 processes, P0 and P1
General structure of process Pi (other process Pj)
do {
entry section
critical section
exit section
reminder section
} while (1);
Processes may share some common variables to
synchronize their actions.
Algorithm 1
Shared variables:
int turn;initially turn = 0
turn = 0 P0 can enter its critical section
turn = 1 P1 can enter its critical section
Process P0
do {
while (turn != 0) ;
critical section
turn = 1;
reminder section
} while (1);
Process P1
do {
while (turn != 1) ;
critical section
turn = 0;
reminder section
} while (1);
Algorithm 2
The problem with algorithm 1 is that it does not retain sufficientinformation about the state of each process; it remembers onlywhich process is allowed to enter its critical section. To remedy thisproblem, we can replace the variable turn with the following array:boolean flag [2];
Shared variables
boolean flag[2];initially flag [0] = flag [1] = false.
flag [0] = true P0 ready to enter its critical section
flag [1] = true Pi ready to enter its critical section
Process P0
do {
flag[0] := true;while (flag[1]) ;
critical section
flag [0] = false;
remainder section
} while (1);
Process P1
do {flag[1] := true;while (flag[0]) ;critical section
flag [1] = false;remainder section
} while (1);
Algorithm 3
Combined shared variables of algorithms 1 and 2.
Process P0
do {
flag [0]:= true;turn = 1;while (flag [1] and turn = 1) ;
critical section
flag [0] = false;
remainder section
} while (1);
Meets all three requirements; solves the critical-section problem for two processes.
Process P1
do {flag [1]:= true;
turn = 0;while (flag [0] and turn=0) ;
critical sectionflag [1] = false;
remainder section} while (1);
Bakery Algorithm
Before entering its critical section, process receives a
number. Holder of the smallest number enters the critical
section.
If processes Pi and Pj receive the same number, if i < j,
then Pi is served first; else Pj is served first.
Critical section for n processes
Bakery Algorithm
Notation < lexicographical order (ticket #, process id #)
(a,b) < (c,d) if a < c or if a == c and b < d
max (a0,…, an-1) is a number, k, such that k ai for i = 0,
…, n – 1
Shared data
boolean choosing[n];
int number[n];
Data structures are initialized to false and 0 respectively
Bakery Algorithm
Process Pi
do {
choosing[i] = true;
number[i] = max(number[0], number[1], …, number [n – 1])+1;
for (j = 0; j < n; j++) {
while (choosing[j]) ;
while ((number[j] !=0) && ((number[j],j) < (number[i],i))) ;
}
critical section
number[i] = 0;
remainder section
} while (1);
Semaphores
Semaphores
Semaphore S – integer variable
can only be accessed via two indivisible (atomic)
operations
wait (S):
while S 0 do no-op;
S--;
signal (S):
S++;
Critical Section of n Processes
Shared data:
semaphore mutex; //initially mutex = 1
Process Pi:
do {wait(mutex);
critical section
signal(mutex);remainder section
} while (1);
Drawback: Spin until lock (spinlock semaphore), CPU wasted
Semaphore Implementation
Define a semaphore as a record
typedef struct {
int value;
struct process *L;
} semaphore;
Assume two simple operations:
block suspends the process that invokes it (i.e.) running to
wait state
wakeup(P) resumes the execution of a blocked process P
(i.e.) wait to ready state
Implementation
Semaphore operations now defined as
wait(S):S.value--;
if (S.value < 0) {
add this process to S.L;block;
}
signal(S): S.value++;
if (S.value <= 0) {
remove a process P from S.L;wakeup(P);
}
Semaphore value can be negative
Magnitude = no. of process waiting in the list
Operating System Concepts
Deadlock and Starvation
Deadlock – two or more processes are waiting indefinitely for
an event that can be caused by only one of the waiting
processes.
Let S and Q be two semaphores initialized to 1
P0 P1
wait(S); wait(Q);
wait(Q); wait(S);
signal(S); signal(Q);
signal(Q) signal(S);
Starvation – indefinite blocking. A process may never be
removed from the semaphore queue in which it is suspended.
Two Types of Semaphores
Counting semaphore – integer value can range over
an unrestricted domain.
Binary semaphore – integer value can range only
between 0 and 1; can be simpler to implement.
Classical Problems of Synchronization
Classical Problems of Synchronization
Bounded-Buffer Problem
Readers and Writers Problem
Dining-Philosophers Problem
Bounded-Buffer Problem
Shared data
semaphore full, empty, mutex;
full – no. of full buffers
empty – no. of empty buffers
mutex – no. of process that can enter a critical section
simultaneously
Initially:
full = 0, empty = n, mutex = 1
Bounded-Buffer Problem - Producer
Process
do {
…
produce an item in nextp
…
wait(empty);
wait(mutex);
…
add nextp to buffer
…
signal(mutex);
signal(full);
} while (1);
Bounded-Buffer Problem - Consumer
Process
do {
wait(full)
wait(mutex);
…
remove an item from buffer to nextc
…
signal(mutex);
signal(empty);
…
consume the item in nextc
…
} while (1);
Readers-Writers Problem
Shared data
semaphore mutex, wrt;
Initially
mutex = 1, wrt = 1, readcount = 0
Readers-Writers Problem - Writer Process
wait(wrt);
…
writing is performed
…
signal(wrt);
Readers-Writers Problem - Reader Process
wait(mutex);
readcount++;
if (readcount == 1)
wait(wrt);
signal(mutex);
…
reading is performed
…
wait(mutex);
readcount--;
if (readcount == 0)
signal(wrt);
signal(mutex):
Dining-Philosophers Problem
Shared data
semaphore chopstick[5];
Initially all values are 1
Dining-Philosophers Problem
Philosopher i:
do {
wait(chopstick[i])
wait(chopstick[(i+1) % 5])
…
eat
…
signal(chopstick[i]);
signal(chopstick[(i+1) % 5]);
…
think
…
} while (1);
Dining-Philosophers Problem
Limitations: It has the possibility of creating a deadlock.Suppose that all five philosophers become hungrysimultaneously, and each grabs her left chopstick. All theelements of chopstick will now be equal to 0. When eachphilosopher tries to grab her right chopstick, she will be delayedforever.
Solution to the dining-philosophers problem that ensuresfreedom from deadlocks are:
Allow at most four philosophers to be sitting simultaneously at thetable
Allow a philosopher to pick up her chopsticks only if bothchopsticks are available
an odd philosopher picks up first her left chopstick and then herright chopstick, whereas an even philosopher picks up her rightchopstick and then her left chopstick.
Reference
A. Silberschatz, P.B. Galvin & G. Gagne, “Operating system
concepts”, Sixth Edition John Wiley, 2005.