Understanding Processes and Threads in OS
Understanding Processes and Threads in OS
3
Processes and Threads
The process concept helps to explain, understand and organize execution of programs
in an OS. A process is an execution of a program. The emphasis on 'an' implies
that several processes may represent executions of the same program. This situation
arises when several executions of a program are initiated, each with its own data.
and when a program that is coded using concurrent programming techniques is in
execution.
A programmer uses processes to achieve execution of programs in a sequential
or concurrent manner as desired. An OS uses processes to organize execution of
programs. Use of the process concept enables an OS to execute both sequential and
concurrent programs equally easily.
We discuss two views of processes in this Chapter: the programmer view, and the
OS view. In the programmer viewwe discuss how concurrent processes are created
and how they interact with one another to meet a common goal. In the OS view we
discuss how an OS creates processes, how it keeps track ofprocess states, andhow
it uses the process state information to organize execution of programs.
A thread is an execution of a program that uses the environment of a process,
that is, its code, data and resources. If many threads use the environment of the same
process, they share its code, data and resources. An OS uses this fact to reduce its
overhead while switching between such threads.
3.1 PROCESSES AND PROGRAMS
A programis a passive entity that does not perform any actions by itself: it has
to be executed to realize the actions specified in it. Aprocess is an execution of a
program; it actually performs the actions specified in aprogram. An operating system
considers processes as entities for scheduling. This is how it realizes execution of
user programs.
Processes and Threads 85
(a) (b)
Table 3.1shows two kinds of relationships that can exist between processes and
programs. A one-to-one relationship exists when a single execution of asequen
tial program is in progress. The programn consistsS of a main program and a set of
functions. During ts execution, control flows between the main program and the
functions according to the logic of the program. The OS is not aware of the existence
of functions. Hence execution of the program constitutes a single process. A many
to-one relationship would exist between many processes and this program if several
executions of the program are inprogress at the same time.
Table 3.1 Relationships between processes and programs
Relationship Examples
One-to-One A single execution of a sequential program
Many-to-one Many simultaneous executions ofa program,
Execution of a concurrent program
86 Operating Systems
register
copy.
sample
buffer area
disk.
data logger write
house
\keeping)
copy_sample disk _write housekeeping
(a) (b)
Fig. 3.2 Real time application of Section 2.7: (a) Process tree, (b) Processes
Advantage Explanation
Computation Creation of multiple processes in an application provides
speed-up multi-tasking. Its benefits are similar to those of multipro
gramming; it enables the OS tointerleave execution of /O
bound and CPU-bound processes in an application, thereby
providing computation speed-up.
Priority for A child process created to perform a critical function in an
critical functions application may be assigned a higher priority than other
functions. Such priority assignments may help the OS to
meet real-time requirements of an application.
Protecting parent The OS cancels a child process if an error arises during its
process from errors execution. This action does not affect the parent process.
command processor uses this feature to advantage. It creates a new process to exe
cute a user program. This way the command processor does not come to any harm
even if the program malfunctions.
CPU state is comprised of contents of the PSW fields and the CPU
registers.
As described in Section 2.1.1. the CPUstate contains information like
of the instruction to be executed next, the condition code, which is address
alsocalled/lags.
and contents of CPU registers. The CPUstate changes as the
program execution
procceds. The code, data and stack of the process constitute itsaddress space.
3.3.2 Controlling Processes
A process is a program execution. Hence following Def. 3.1, a process has the five
components process id, code, data, stack, and CPU state. The process uses the CPU
when it 1s scheduled. It also uses other resources. These include system
resources
1ke memory and user-created resources like files. The OS has to maintain informa
tion about all these features of a
process.
The OS view of a process consists of two
parts:
" Code and data areas of the process, including its stack, and resources
allocated
to it
Process environment Also called the process context, the process environment
contains the address space of a process, i.e., its code, data, and stack, and all infor
mation necessary for accessing and controlling resources allocated to the process.
The OS creates a process environment by allocating memory to the process, loading
the process code in the allocated memory and setting up itsdata space. The OS also
94 Operating Systems
puts in information concerning access to resources allocated to the process, and its
nteraction with other processes and with the OS.
Table 3.4 deseribcs components of he process environment. Contents of the
proccss cnvironment change during exccution of a prOceSs duc to actions like fle
open and close, and dynamic creation and destruction of data by the process.
Table 3.4 Components ot the pocOSs environment
Process environment
Process environment consistsof the code and data of the process and all information
necessary for operationof the process.
Component Description
Code and data Code of the program, including its functions and proce
dures, and its data, including the stack.
Memory allocation Information concerning memory areas allocated to the
information process. This information is used to implement memory
accesses made by the process.
Status of file process Pointers to files opened by the process, and current pos0
Ing activities tions in the files
Process interaction All information necessary to control interactions of the
information process with other processes, e.g., interprocess meSsages,
signal handlers, ids of parent and child processes.
Resource information Information concerning resources allocated to a process.
Miscellaneous infor Miscellaneous information needed for interaction of a pro
mation cess with the OS.
Process control block (PCB) The process control block is a kernel data structure
that contains information concerning the first and fifth component of Def. 3.1, that
is, process id and CPUstate. Details of the PCB are described in Section 3.3.4.
The kernel uses three fundamental functions to control processes:
1. Scheduling: Select the process to be executed next on the CPU.
2. Dispatching: Set up execution of the selected process on the CPU.
3. Context save: Save information concerning a running process when its
execu
tion is suspended.
The scheduling function selects a process based on the scheduling policy in force.
Dispatching involves setting up the environment of the selected process, and loading
information into the CPUso that CPUbegins (or resumes) execution of instructions
in the process code. The context save function performs
housekeeping whenever a
process releases the CPU or is preempted. It saves information concerning the CPU
state and the process environment so that execution of the process may be
resumed
sometime in future. Effectively, context save is the converse of the dispatching tunc
tion.
Processes and Threads 95
Event
Context save
Event handling
Scheduling
Dispatching
Fig. 3.5 Fundamental functions to control processes
The schematic in Figure 3.5 illustrates use of these functions by the kernel when
an event occurs. Occurrence of an event invokes the context save function and an
appropriate event processing routine. The event processing actions may activate
some processes, hence the scheduling function is invoked to select a process and
the dispatching function transfers control to the selected process.
Definition 3.2 (Process state) The process state is an indicator of the nature of the
Current activity in aprocess.
Table 3.5 describes four fundamental process states. A process is in theblocked
state if it has made a resource request to the kernel and the request is yet to be
granted, or if it wishes to wait until some event occurs. The process enters theready
state when the request is granted or the event occurs, and it enters therunningstate
when it is dispatched. The process enters the terminated state when its execution
completes or when it is terminated by the OS for [ome reason.
A conventional computer system contains one CPU, so at most one process can
be in the running state. Any number of processes can however exist in the blocked,
ready and terminated states. An OS may define more process states to simplify its
Own functioning or to support additional functionalities like swapping.
Process state transitions A state transition for a process P, is a change in its state.
A state transition is caused by the occurrence of some event in the system. When a
process P, in the running state makes an /O request, it has toenter the blocked state
until its LVO operation completes. Atthe end of the I/O operation P,'s state changes
from blocked to ready. Similar state changes occur when a process makes some
96 Operating Systems
State Description
Running A CPUiscurrently executing instructions in theprocess code.
Blocked The process has to wait untila resource request made by it is granted.
or it wishes to wait until a specific event occurs. A CPU should not
be allocated to it until its wait is complete.
Ready The process wishes to use the CPUto continue its operation; how
ever, it has not been scheduled.
Terminated The operation of the process. i.e., the execution of the program rep
resented by it, has completed normally, or the OS has aborted it.
request that cannot be satisfied by the OS straightaway. The process state changes to
blocked when the request is made, i.e., when the request event Occurs, and changes
toready when the request is satisfied. Aready process becomes running when the
CPUis allocated to it. A running process becomesready when it is preempted either
because ahigher priorityprocess becomes ready or because its time slice elapses (see
Sections [Link] and 2.6).
Figure 3.6 shows the fundamental state transitions for a process. Table 3.6 sum
marizes causes of state transitions. A new process is put in the ready state after all
resources required by it have been allocated. It may enter the running, blocked and
ready states a number of times due to events described in Table 3.6. Eventually
enters the terminated state.
resource or
dispatching, wait request
preemption
new
procesS Ready Blocked
resource granted
or wait completed
Fig, 3.6 Fundamental state transitions for a process
Example 3.3 Consider the time sharing system of Example 2.12, which uses a
slice of 10 msec. It contains two programs P and P.. P, has a CPU burst oftinie1
msec followed by an VO operation that lasts for 100 msec, while P has a CPU burst
of 30 msec followed by an I/O operation that lasts for 60 msec.
Execution of >i
and P2 was described in Figure 2.2 1and Table 2.13. For simplicity, we
assume thal
processes created to execute programs P and P> are themselves called P and P2.
Processes and Threads 97
New state
Time Event Remarks P P
P is scheduled running ready
10 P ispreempted P isscheduled ready running
20 P is preempted P is scheduled running ready
25 P starts /O P is scheduled blocked running
35 P is preempted blocked ready
P is scheduled blocked running
45 PP starts I/O blocked blocked
125 VOinterrupt P, becomes ready ready blocked
P is scheduled running blocked
Swapped state and blocked to blocked swapped state are caused by a swap-out action.
The reverse transitions take place when these processes are
swapped back int0 the
memory. The blocked swapped ’ ready swapped transition takes place if the request
for which the process was waiting is granted even while the
state, for example if a resource for which it was blocked isprocess
is ina suspended
granted to it. However,
the process continues to be swapped out. When it is
swapped back into the memory,
its state would change to ready and it would compete with other
the CPU's attention. ready processes for
completion Termi
Running nated
resource or
dispatching, wait request
preemption
new
Ready resource granted
process
or wait completed Blocked
Fig. 3.7 Process states and state transitions using two swapped states
The processcontrol block (PCB) contains all information pertaining toa process that
is used in controlling its operation--such as its id, priority, state, PSW and contents
of CPU registersas also information used in accessing resources and implementing
communication with other processes. Table 3.8 describes fields of the PCB data
structure.
The priority and state information is used by the scheduler. It passes the id of the
selected process to the dispatcher. For a process that is not in therunning state, the
PSW and CPUregisters fields together contain a snapshot of the CPUwhen it was
last released by the process, i.e., they hold contents of the various control and data
registers of the CPUwhen the process got blocked or was preempted. Execution of
the process can be resumed by simply loading this information from its PCB into the
100 Operating Systems
[Link] action would be performed the next time this process is to be dispatched.
The event information field of the PCB plays an important role in effecting appro
priate state transitions in the system. Consider a process P, that is blocked on an VO
operation. The event information field in P's PCB indicates the id of the device, say
device d, on which the VO operation is being performed. When the IO operation
on device d completes, the kernel must find the process that awaits that event and
change its state to ready. eventinformation field of P;'sPCB indicates that it awaits
the end of VO on device d, so the kernel concludes that the state of P, should be
changed from blocked to ready.
Process switching Functions 1,3 and 4 of Example 3.4 collectively perform switch
ing between processes P and P. Switching between processes also occurs when a
running process gets blocked due to a request or gets preempted. An event does not
lead to switching between processes if occurrence of the event either causes a state
transition for a lower priority process, or does not cause any state transition (e.g., if
the event is caused by a request that is satisfied straightaway). In the former case, the
scheduling function selects the interrupted process itself for dispatching. In the latter
case, scheduling need not be performed at all; after event processing, control can be
given to the dispatcher, which would simply dispatch the interrupted process.
Switching between processes is more than saving the CPUstate of one process
and loading CPUstate of another process. The process environment needs to be
switched as well. Saving and loading of memory management information is an
expensive part of process switching, particularly when virtual memory is used. Some
switching over
computer systems provide special instructions to reduce the processregisters. We use
CPU
head, e.g.. an instruction that saves or loads the PSW and all
information that needs to be
the term state information of a process to refer to all the switching overhead depends
saved and restored during process switching. Process
on the size of this information.
well. The newly scheduled
Process switching has some indirect overhead as
space in the cache, hence it performs
process does not have any part of its address operation
poorly until it builds sufficient information in the cache. Virtual memory
buffers do not contain any information
isalso poorer initially because translation
relevant to the newly scheduled process.
6 Operating Systems
action is not performed if'the resource can bc allocated straightaway. In this. Case, the
interrupted process is simply dispatched again. When a process releases aresource,
released
an wnblock action is performed ie' some other process Is waiting lor the
source, followed by scheduling and dispatching because the unblocked process ma.
resource. Again, schedl:
have a higher priority than the process that released the
the event.
is skipped if no process is unblocked due to
THREADS
Since a thread is a program execution, it has its own stack and CPUstate (see
Def. 3.1). We use the phrases 'thread(s) of a process' and 'parent process of a threa
to describethe relationship between a thread and the process whose environment
uses. Threads of the same process share code, data and resources with one anoui
The process abstraction continues lo be used as before except that processes typically
have distinct code anddata parts.
Figure [Link] depicts the relationship between threads and processes. Process?i
has three hreads represented by he wavy lines. The kenel allocates a stack a
Processes and Threads 107
Threads
Process
P
Stacks
memory resource fi le
info info p0inters
Environment of
Environment of Thread control
process P; process P PCB
blocks (TCBS)
(a) (b)
a thread control block (TCB)to each thread. The threads execute within the envi
ronment of P;. The OS is aware of this fact, so it saves only the CPUstate and the
stack pointer while switching between threads of the same process. In most com
puter systems, the stack pointer is maintained in a CPU register, hence only the CPU
state needs to be switched. Use of threads effectively splits the process state into two
parts- -resource state remains with the process while execution state is associated
with athread. The cost of concurrency within the environment of aprocess is now
merely replication of the execution state for each thread. The resource state is not
replicated.
Thread states and state transitions Barring the difference that threads do not have
resources allocated to them, threads and processes are analogous. Hence thread states
state transi
and thread state transitions are analogous to process states and process
process
tions, When a thread is created, it is put in the ready state because its parent when
enters the running state
already has the necessary resources allocated to it. It
state because of resource requests, be
it is scheduled. It does not enter the blocked state
does not make any resorce requests; however, it can enter the blocked
cause it example, if threads were used
requirements. For
because of process synchronization Example 3.1, thread disk write would
data logging application of
in the real time data samples exist in bufer area.
have to enter the blocked state if no
application process can create many threads to execute
Advantages of threads An many
to see the advantages of this scenario over creation of
its code. It is interesting code. The fundamental advantage is that of low
application another thread of the same
processes to execute the CPU from one thread to
overhead while switchingthe switched only while switching between threads of
is
process. The resource state
different processes. within a process. It can provide computa
concurrency
Use of threads provides
108 Operating Systerms
speed-up-if one thread of aprocess blocks on an I/Ooperation, the CPI
tion
be switched to another thread of the same process. Use of threads can also simplify
the design and coding of applications that need to perform Concurrent servicing of
or a banking system
requests. For example, in an airline reservation system OS would schedule th
thread can be created to handle each new request. The
complex logic to ach:
threads to provide concurrency. This arrangement obviates
concurrent processing of requests.
soms
Creation of many processes within the application code can achieve the
effect. However, there is one significant difference. Concurrent activities, whether
processes or threads, have to communicate or synchronize with one another. When
these activities are implemented by processes, communication or synchronization
involves the kernel. Processes have to make system calls to indicate their com
munication or synchronization requirements to the kernel. However, threads of a
process share their data space. Hence they can communicate or synchronize using
shared memory, thereby eliminating expensive system calls. Therefore in the real
time application of Example 3.1, it would be preferable to use threads to implement
functions 1and 2, which share the buffer area.
Table 3.9 summarizes the advantages ofthreads. As discussed in Example 3.1, an
application can create many threads to obtain concurrency and simplify its function
ing. Threads can be assigned specific functions. They can also be created to perform
concurrent servicing of requests received by a server, e.g., in an airline reservation
system or abanking system. In such cases, threads would execute the same function.
Advantage Explanation
Low overhead Thread state consists only of the state of a
Resource allocation state and communication state computation.
is not a part
of thread state, which leads to low switching
Speed-up overhead.
Concurrency within a process can be realized by creating many
threads in it. This technique can speed up execution of an appli
cation on both uniprocessors and
Efficient multiprocessors.
Threads of a process can communicate with one another
communication through shared data space, thus avoiding the overhead of sys
tem calls forcommunication.
Coding for use of threads Threads should ensure
(see Section 3.2.1). Correctness ofcorrectness
of data sharing and
synchronization
facet. Functions or subroutines that use data sharing also has anouiC
static or global data to carry values d
ner suCcessive activations produce
because the concurrent invocations incorrect results when invoked concurrenti
effectively perform data sharing without muo
Processes and Threads 109
P PCB
PCB
W
Scheduler
Selected TCB
selects one ready thread; the dispatcher uses the PCB pointer in its TCB to check if
the selected thread belongs to a different process than the interrupted thread. If so,
itsaves the context of the process to which the interrupted thread belongs, and loads
the context of the process to which the selected thread belongs. It then dispatches the
selected thread. Actions to save and load the prOcess context are unnecessary if both
threads belong to the same process. This feature reduces the switching overhead.
Advantages and disadvantages of kernel-level threads A kernel-level thread is like
a process except that it has a smaller amount of state information, i.e., it has a
"thinner state. This similarity between threads and processes is
convenient for
programmers-programming for threads is no different from programming for pro
cesses. In a multiprocessor system, kernel-level threads provide parallelism (see
Section 3.2.2), i.e., several threads belonging to a process can be
scheduled simul
laneously, which is not possible using the user-level threads described in the next
section,so it provides better computation speed-up than user-level
However, handling threads like processes has its disadvantagesthreads.
too. Switching
between threads is performed by the kernel as a result of
incurs the overhead of event handling even if the event handling. Hence i
interrupted thread and the selected
thread belong to the same process. This feature limits
Overhead. the savings in the switchlng
P P
Scheduler
Selected PCB
operate at any time. To dispatch' the thread, the CPU state of the thread
become the CPU state of the process, and the process stack pointer
should
to the thread's stack. Since the thrcad library is a part of a process, the
shoulpointd
in the non-privileged mode. Hence athread cannot be dispatched by CPU is
information into the PSW; the thread library has to use non-privilegedloading new
to change PSW contents, so it loads the address of the thread's stack into
address register, and executes a branch instruction to transfer control tothe
thAstack instructions
instruction of the thread. The next example illustrates interesting situations
scheduling of user-level threads. during
Example 3.6 Figure 3.14 illustrates how the thread library manages three threads in
aprocess P. The codes N, Rand Bin the TCBs represent the states running. Tead
and blocked, respectively. Process P is in the running state and the thread library
is executing. It dispatches thread hË. Process P; is preempted sometime later by the
kernel. Figure 3.14 (a) illustrates states of the threads and of process P;. Thread h
is in the running state, and process P; is in the ready state. Thread h| would resume
its operation when process P, is scheduled next. The line from hË's TCB to P's PCB
indicates that hË's TCB is currently mapped into P,'s PCB. This fact is important for
the dispatching and context save actions of the thread library.
hË hT h3 hË h2 h3 hË h2 h3 hË hy h3
P P P P
PCB
of P Ready Running Running Blocked
ds
Thread h is in the ready state in Figure 3.14(a), so its TCB contains the code h
Thread h3 awaits a synchronization action by hi, so it is in the blocked state.
TCB contains the code B, and hË to indicate that it is avwaiting an event that
synchronization action by hË. Figure 3.14(b) shows the situation when the kenis
dispatches P; and changes its state to running.
The thread library overlaps operation of threads using the timer. When thread hi W
'scheduled', it would have requested an interrupt after a smallinterval of time. wen
the timer interrupt occurs, it gets control through the event handling routine oI
Processes and Threads 113
kernel for timer interrupts, and decides to preempt h1. So it saves the CPUstate in
h's TCB, and 'schedules' hT. Hence the state codes in the TCBs of hË and h2 change
to Rand N, respectively (Figure 3. 14(c)). Note that thread scheduling performed by
the threadlibrary is invisible to the kerncl. Al through these events, the kernel sees
process P, in the running state.
Auser thread should not make a blocking system call; however, let us see what would
happen if h2 made a system call to initiate an /O operation on device dz, which is a
blocking system call. The kernel would change the state of process P, to blocked and
note that it is blocked due to an l/O operation on device dz (Figure 3.14(d). Sometime
after the /O operation completes, the kernel would schedule process P, and operation
of h2 would resume. Note that the state code in hz's TCB remains N, signifying the
running state, all through its /O operation!
Scheduling
Thescheduling policy used in an operating system influences user service, eficient
use of resources and system performance. Scheduling policies use the fundamen
tal techniques of preemption, reordering of requests and variation of time slice to
achieve their goals. We discuss how these techniques are used in classical non
preemptive and preemptive scheduling policies.
An operating system has to adapt its functioning to the availability of resources
in the system; it uses a combination of three schedulers called long-term, medium
term and short-term schedulers for this purpose. An important issue in practical
scheduling is fairness in user service. We discuss how operating systems incorporate
fairness by dynamically varying the priority of a process. We also study scheduling
in a real time environment.
Performance analysis of scheduling policies is important for tuning the pertor
mance of a scheduling policy and for comparing alternative policies. We discuss
important elements of performance analysis.
4.1 PRELIMINARIES
Process P Pp P, P4 Ps
Arrival time 2 3 5
Service time 3 3 2 5 3
FCES scheduling Requests are scheduled in the order in which they arrive m
the system. The list of pending requests is organized as a queue. The sCheuu
always schedules the first request in the list. An example of FCFS scheduling
batch processing system in which jobs are ordered according to their arrival times
(or arbitrarily if their arrival times are identical), and results of a job are releasedto
a user immediately on completion of a job. Example 4.1 illustrates operation ofan
FCFS scheduler.
Example4.l Top half of Figure 4.2 shows the scheduling decisions perforned by thí
FCFS policy for the processes of Table 4.2, Left half of Table 4.3 summar1zeS
formance of the FCFS scheduler. The Completed column shows id of the completed
process and its turn around time (ta) and weighted turn around ((w). Note that consid-
erable variation exists in the weighted turn arounds. This variation would have been
larger if processes suffering large turn around times were short, e.g.. the weightedturn
Scheduling 149
around of P, would have been large if its execution requirement was I.0 second or 0.5
seconds. Mean ta and w(i.e., ta and w) are shown below the table.
P
First-come
first-served P
(FCFS) PA
Ps
P
Shortest P
request next P
(SRN) P4
Ps
5 10 15
FCFS SRN
Completed Processes Sche Completed Processes Sche
Time id ta W in system duled id ta in system duled
P {Pi} P
P 3 1.00 {e, Ps} P2 P 3 1.00 {P, P} P
P 2 1.00 (P, Pa} P
6 P 4 1.33 {P3,Pa} P3
P 2.50 {Pa} PA P 6 2.00 {Pa} PA
13 P 1.60 {Ps} Ps P 8 1.60 {Ps} Ps
16 P 7 2.33 P 2.33 {}
ia = 5.40 seconds ta= 5.20 seconds
W= 1.75 W= 1.59
Example 4.1 shows that wide disparity exists in the service received by requests
in FCFS scheduling. From this, onecan conclude that short requests (processesPs
and P;) may suffer high weighted turn arounds, i.e., poorer service, compared to
other requests (process P). In a batch processing system, jobs in the batch may
be re-ordered to reduce turn around times and weighted turn arounds of individual
jobs. However this would not reduce the spread of turn around times or increase the
throughput.
Shortest request next (SRN) scheduling The SRN scheduler always schedules the
50 Operating Systenns
requests. Thus, arcquest remains pending until all shorter
shortest of arrived
have been serviced.
Example 4.2 The bottom half of Figure 4.2 shows the scheduling decisions per-
requests
formed by the SRN policy forthe processes of Table 4.2. The right half of Table 4.3
summarizes pertormance of the SRN scheduler. The mean turn around and the mean
weighted turn around are better than in FCFS scheduling because short requests tend
to receive smaller turn around times and weighted turn arounds than in FCFS schedul.
weighted turn are
ing. This degrades the service to long requests however their
donot increase much because their service times are large. The throughput is hiok
than in FCFS scheduling except at the end of the schedule, where it is identical
It is dificult to implement the SRN policy in practice because service times of
processes are not known apriori. Many systems expect users toprovide estimates of
service times of processes. However, results obtained using such data are erratic if
users do not possess sufficient experience in estimating service times. Dependence
on user estimates also leaves the system open to abuse or manipulation, as users
might try to obtain better service by specifying low values for service times of their
processes. Another practical aspect where SRN scheduling does not fare wellis in
the service offered to long processes. A steady stream of short processes arriving in
the system can deny CPUto long processes indefinitely. This is starvation.
Highest Response Ratio Next (HRN) The HRN policy computes the response
ratios of all processes in the system according to Eq. (4.1) and selects the process
with the highest response ratio.
Pu
Pi2
P3
Pi4
Ps
10 15 time
Fig. 4.3 Operation of highest response ratio (HRN) policy
P
Round-robin P:
(RR)
P
PA
Ps
Least P
completed next P.
P:
(LCN) P
Ps
P
Shortest
time to go
(STG) P
P
5 10 15
Fig. 4.4 Scheduling using preemptive scheduling policies
turn around because three processes exist in the system through most of its life. P
receives the best weighted turn around since no other process exists in the system
during the early part of P,'s execution. Thus weighted turm arounds depend on the
load in the system.
Effectiveness of RR scheduling depends on two factors: choice ofô. the time
slice, and nature of processes in the system. As discussed in Chapter 2, if a system
contains n processes and each request by a process consumes exaclyð seconds, the
response time (r) for a request is
n=n X (o + Þ) (4.2)
where o is the scheduling overhead per scheduling decision. Since all processes
requests--the
may not be active at all times-some will be blocked for I/O or other
response time will be governed by the number of active processes rather than byn.
Twoother factors that can affect rt are the variation in CPUtime required by different
requests, and the relationship between Ó and the CPUtime required by a request. Eq.
(4.2) assumes that each request consumes exactlyð seconds and produces a response.
more than
If a request needs more CPU time than ò, then it will have to be scheduled
ofð, rt
once before it can produce a response. Therefore, in certain regions of valuesfact.
4.5 illustrates this
for a request may increase even as Óis reduced. Example
154 Operating Systems
Table 4.5 Performance of preemptive scheduling policies (C: Completion time of process)
Example 4.5 An OS contains 10 identical processes that were initiated at the same
time. Each process contains 15 identical requests, and each
request
msec of CPUtime. A request is followed by an I/O operation that consumes 20
msec. The system consumes 2 msec in CPUscheduling. For d>20 consumes
10
msec, the first
request by the first process receives a response time of 22 msec and the first request
by the last process receives a response time of 220
msec, so the average response
time is 121 msec. A subsequent request by any
10 x (2+ 20) 10 msec = 210msec since the process process receives a response time of
spends 10 msec in an VO wail
before making the next request. For d= 10 msec, a request would be
10 msec. When scheduled again, it would execute for 10 preempted ater
msec and produce results, so
the response time for the first process is
= 10 x (2 + 10) +(2 + 10)=132
msec
and that for the last process is
= 10 x (2+ 10)+ 10 x (2+
10)= 240 msec.
A subsequent request receives a response time of 10 x
(2+
230 msec. Figure 4.5 illustrates the variation of average 10) + 10time
response x (2+I0)
to second and
subsequent requests for different values of 8. Table 4.6 summarizes performancet
the system for different values of . As expected, the overhead is higher forsmaller
values of 8.
Policies using resource consumption
information
Policies using resource consumption information aim at eliminatin8 some problems
of preemptive policies discussed so far, e.g. poor weighted turn arounds ofshort prë
cesses and starvation of long processes. We discuss the following three scheduling
policies:
1. Least Completed Next
2. Shortest Time to Go (LCN) scheduling
3. Response Ratio
(STG) scheduling
scheduling.
Scheduling 155
0.3
Response
time
(secs)
0.2
0.1 +
5 10 15 20 25
Time slice (msec) ’
Fig. 4.5 Variation of average response time with time slice
Least completed next (LCN) The LCN policy schedules the process that has con
sumed the least amount of CPU time. Thus, the nature of a process, whether CPU
bound or VO-bound, and CPU time requirement of a process do not influence its
progress inthe system. All processes make approximately equal progress in terms of
the CPU time consumed by them, so short processes are guaranteed to finish ahead
of long processes. However, this policy has the familiar drawback of starving long
processes of CPU attention. It also neglectsexisting processes if new processes keep
arriving in the system. So even not-so-long processes tend to suffer starvation or
larger turn around times.
Example 4.6 Operation of the LCNscheduling policy for the five processes shown in
Table 4.2 is summarized in the middle part of Table 4.4. The scheduling information
used by the policy consists of a pair (process id,CPU time consumed. We use the
notation P,:j, where P is aprocess id and t, is the CPU time consumed by it, to denote
this informaion in the column Processes. The scheduler analyses this information and
selects the process that has consumed the least amount of CPUtime. In case of a tie,
selects a process that has not been serviced for a longer period of time.
The turn aroundtimes and weighted turn arounds of the processes are shown in the
second part of Table 4.5. Processing of P,P and P4 is delayed because new processes
156 Operating Systems
before these processes can
arrive in the system and obtain CPU service
Example 4.7 The right part of Table 4.4 summarizes performance of the STG schedul.
ing policy for the five processes shown in Table 4.2. The scheduling information usd
by the policy consists of a pair (process id, CPU time needed for completion).We use
the notation P:tj, where P is a process id and t; is the CPU time needed by it for
completion, to denote this information in the column Processes. The scheduler uses
this information for selecting the process that requires the least amount of CPU time
for completion. In case of a tie, it selects a process that has not been serviced for a
longer period of time.
The third part of Table 4.5 shows the turn around times and weighted turn aroundS
of the processes. Note that processes P,P and Ps obtain good turn around timts
and weighted turn arounds. In fact the turn around times and weighted turn around
of all processes other than Pa are better than those provided by the LCN policyHenc ($e
Example 4.6). This is so because their service times are shorter than that of P4.
executionoc
superior service received by them is at the cost of neglecting PA, whose
not even begin until P; is complete. This neglect of long processes canwerebe sen
toariveal
starkly if another process P% with CPUtime requirement of 6seconds aroundtime
t= l second. Its execution would begin only after P4 completes; its turn
and weighted turn around would be 21 seconds and 3.5, respectively.
4.4 SCHEDULING IN PRACTICE
4.4.1 Long, Medium and Short-term Scheduling system
user-centric and thu
An operating system has to provide a suitable combination of user
requests
singl
centric features. It also has to adapt to the nature and number of A
resources. Therc
are expected to arise in its environment, andtothe availability of Concerns.
scheduler and a single scheduling policy cannot address all itscalled thelong-enn
fore, an OS uses an arrangement consisting of three schedulers
Scheduling 175
Event addresses A process that is blocked on an event is said to sleep on it. Unix
uses an interesting arrangement to activate processes sleeping on an event. Instead of
ECBs (see Section 3.3.6), it uses the notion of an event address. A set of addresses
is reserved in the kernel for this purpose. Every event is mapped into one of these
addresses. When a process wishes to sleep on an event, address of the event is com
puted using a special procedure. The state of the process is changed to blocked and
the address of the event is put in its process structure. This address serves as the
description of the event awaited by the process. When an event occurs, the kernel
computes its event address and activates allprocesses sleeping on it.
This arrangement has one drawback-it incurs unnecessary overhead in some
siuations. Several processes may sleep on the same event. The kernel activates all
of them when the event occurs. The processes must themselves decide whether all
of them should resume their execution or only some of them should. For example,
when several processes sleeping due to data access synchronization are activated.
onlyone process should gain access to the data and other activated processes should
goback to sleep. The method of mapping events into addresses adds to this problem.
Ahashing scheme is used for mapping, hence twoor more events may map into the
same event address. Now occurrence of any one of these events would activate al
processes sleeping on all these events. Only some processes sleeping on the correct
event should resume their execution. Allother processes should go back to sleep.
Process priorities Unix is a pure time sharing operating system, so it uses the
round-robin scheduling policy. However, in a departure from pure round-robin, it
dynamically varies the priorities of processes and performs round-robin only for pro
cesses with identical priority. Thus, in essence, it uses multilevel adaptive schedul
ing. The reasons for dynamic variation of process priorities are explained in the
following.
AUser process executes in the user mode when it executes its own code. It
enters the kernel mode when it startsexecuting the kernel code due to an interrupt
178 Operating Systems
P P P4 Ps Sche
P
P PT P. T P T P T | duled
Time
0.0 60 0 P
1.0 60
90 30 P
2.0 90
105 45 60 0 P
3.0 45 60
82 22 90 30 60 0 P3
3.1 82 22 90 30 60 6 Pi
4.0 76 30 6
98 38 75 15 63 3
4.1 98 38 75 15 63 9 P2
5.0 38 69 0
79 19 94 34 64 4 60 0 P4
6.0 19 34 4 60
69 9 77 17 62 2 90 30 P3
group. Since the effective priority is the inverse of the priority value computed by
the above equation, the priority of aprocess reduces even when other processes of is
group receive CPU time. Example 4.16 illustrates operation of a fair share scheduler.
Example 4.16 Table 4. 14 depicts scheduling of the processes of Table 4.2 by a Unik
like fair share scheduler. Fields P, T and G contain process priority, CPU time cor
sumed by a process and CPU time consumed by a group of processes, respectively.
Two process groups exist. The first group contains processes P,P,B and Ps, W
the second group contains process P4 all by itself. As expected, process P4 reei
a favored treatment when compared to other processes. In fact, in the period I=5t0
I= 15, it receives every alternate time slice. Processes P2, Ps and Ps suffer because
they belong to the same process group. These facts are reflected in the turn around
times and weightedturn arounds of the processes, which are as shown in Table 4.15.
4.7 SCHEDULING IN LINUX
Linux supports both real time and non-real time applications. Accordingly, ithas
two classes of processes. The real time processes have static priorities between 0and
100, where Ois the highest priority. Real time processes can be scheduled intwo
ways: FIFO or round-robin within each priority level. The kernel associates a lag
with each process to indicate how it
shouldpriorities
Non-real time processes have lower be scheduled.
than all real time processes;their
priorities are dynamic and have numerical values between -20 and 19, where -20
is the highest priority. Effectively, the kernel has (100 + 40) priority levels. Tostart
Scheduling 179
P P Pa Ps Sche
Time P C G C G P C G P C G P C duled
60 0 0 0 P
120 30 30 30 30 30 P
150 45 45 105 0 45 45 45 P
134 22 52 142 30 52 112 0 52 52 P
127 11 56 131 15 56 146 30 56 56 P
58 125 7 58 133 15 58 60 0 0 58
6
PA
29 92 3 29 96 7 29 120 30 30 29 P
7 44 135 31 44 107 3 44 90 15 15 44 P
22 97 15 22 83 1 22 134 37 37 82 0 22 Ps
41 108 7 41 101 0 41 96 18 18 131 30 41 PA
10 20 83 3 20 80 0 20 138 39 39 95 15 20 P
11 40 101 1 40 40 98 19 19 107 7 40 P4
12 20 80 0 20 20 138 39 39 83 3 20 P.
13 40 40 40 98 19 19 101 1 40 P
14 20 20 20 39 80 0 20 Ps
15 40 40 40 19 130 30 40 Ps
16
Process P Pp P, P4 Ps
Completion time 5 13 14 16
Turn around time 9
Weighted turn around 1.67 3.67 4.00 1.80 2.33
with, each non-real time process has the priority 0. The priority can be varied by the
process itself through the nice or setpriority system calls. However, special privileges
are needed to increase the priority through thenice system call, so processes typically
use this call to lower their priorities when they wish to be nice to other processes.
In addition to such priority variation, the kernel varies the priority of a process to
reflect itsWO-bound or CPU-bound nature. To implement this, the kernel maintains
information about how much CPU time the process has used recently and for how
long it was in the blocked state, and adds a bonus between 5 and-5 to the nice value
of the process. Thus, a highly interactive process would have an effective priority ot
nice -5, while a CPU-bound process would have an effective priority of nice+5,
Due to the multilevel priority structure, the linux kernelorganizes its scheduling
Operating Systems
The operating system manages switching between threads of the same process by saving only the CPU state and stack pointer since threads share code, data, and resources of their parent process. This minimizes the overhead associated with switching, thereby enhancing performance. However, switching is handled at the kernel level due to event handling, which incurs its own overhead, thereby limiting savings compared to user-level threads .
Threads provide several advantages over processes, including lower overhead when switching the CPU from one thread to another within the same process, as they do not require resource state switching which is needed when switching between different processes. This makes threads more efficient in applications requiring high concurrency. Additionally, threads can communicate and synchronize more efficiently than processes by using shared memory, eliminating the need for costly system calls to the kernel. Overall, threads allow for more seamless and faster concurrent processing within an application compared to processes .
Concurrency in multithreading environments offers potential computation speed-up because threads can execute within the same process space with shared resources, reducing the need for heavy context switching that occurs with process-based concurrency. When one thread is blocked, like in an I/O operation, another thread in the same process can continue executing, utilizing CPU time effectively. This transition incurs less overhead than process-based switching, thereby enhancing system throughput and efficiency .
Preemptive scheduling policies impact system performance by ensuring that the CPU is allocated in a manner that can switch to handling new requests before completing the current ones. This can improve system responsiveness and ensure fairness, especially under multitasking environments. However, such policies might cause longer processes to suffer from increased waiting times due to frequent preemptions. Policies like Least Completed Next (LCN) attempt to balance the load by focusing on processes that have consumed the least CPU time, but they can still lead to starvation for longer processes .
Thread state transitions mirror process state transitions in that when a thread is created, it enters a ready state due to pre-allocated resources by its parent process, and it moves to the running state when scheduled. Unlike processes, threads do not enter a blocked state due to resource requests since they don't make such requests separately. Threads can still be blocked due to synchronization needs, showing that while they behave similarly to processes, their resource handling is intrinsic to their parent process's resources .
Kernel-level threads have limitations in that switching between them involves the kernel and incurs event handling overhead, even if the interrupted and selected threads belong to the same process. This reduces the savings on switching costs that threads are typically supposed to achieve compared to processes. Consequently, while kernel-managed threads allow for simultaneous scheduling and potentially increases computation speed-up, the involvement of the kernel in switching processes limits efficiency gains .
The thread library is crucial for managing user-level threads as it handles thread creation, scheduling, and switching internally without kernel intervention. This library contains the logic for scheduling decisions and performs what is viewed as mapping each thread's control block (TCB) into the process control block (PCB). This setup allows for efficient thread management but also means that issues with blocking conditions for individual threads can affect the entire process's execution .
In algorithms like Highest Response Ratio Next (HRN) scheduling, a higher response ratio can lead to longer processes being selected ahead of shorter ones because the response ratio takes into account the wait time relative to the service time. A long process that has waited sufficiently long can have a higher ratio than a shorter process that has only just arrived. This approach aims to balance fairness by occasionally giving priority to longer processes that have been waiting, but may inadvertently delay other shorter tasks .
User-level threads offer advantages mainly due to their operation being entirely within the process's own memory. This means the kernel does not handle their scheduling; instead, a thread library linked to the process manages it. Consequently, there is no kernel overhead during thread scheduling in user-level threads. Each thread can be managed based on its execution state without invoking expensive system calls, leading to potentially better performance in CPU-bound applications .
User-level threads manage scheduling through a thread library linked to the application process, which operates without kernel involvement. The library handles creating, scheduling, and switching between threads within the process itself. While this can result in lower overheads and faster context switching compared to kernel-level threads, a drawback is that the kernel is unaware of individual thread states. If one thread makes a blocking system call, it blocks the entire process, affecting all associated threads .