Unie HL
3 Linkers and Loaders
‘3a: Introduction
4 What is loader ?
‘Aus: Loader is # wilty program which takes objet code as input
repures ft forexestion and Tass the execuable code into th memery
‘Thus loader is actully responsible for inating the exeation process,
2 Discuss four atereat functions of loader.
SMP: Ap, nas 4)
‘Ans. The louder i responsible for the activites such as allocation,
linking, relocation and lading
1) Wallets she apace for program in the memory, by eating the
sizeof the program. This stv is called allocation.
2) resolves te symbolic references (codeldata) beeen the eet
modules by assigning all the user subroutine and brary subroutine
adresses, Ths activity is elle linking
3) There are some addtess dependent locations in the program, such
adéress constants must be adjusted according to allocated space,
such setivity done by loader is called relocation,
4) Finally it places all the machine instructions and data of
comesponding programs and subroutines into: the memory. Ths
program now becomes ready for execution, this activity is called
loading.
32 Sates and Haters
Loader Schemes!
3 What are types of londers ? Explain compile and go loader
scheme with advantages and disadvantages, ca[S0 : Apia, Marks 6]
‘Ans. + Types of Loaders :
‘Based on various functionalities of the loader, there are various types of
loaders, which are known as loading schemes. Various loaders sebemes
1, Compile and Go
3, Absolute Loader
5. Relocating Loader:
CComplle and go Loader :
2 General Loader Scheme
4. Subroutine Linkage
6. Direct Linkage Loader
‘+n this ype of loader, the insrction is readline by line, its machine
code is obtained and itis dveedy put in the main memory at some
known address
‘2 That_means the assembler runs in one part of memory and the
assembled machine insructions and data i directly put into their
signed memory locations .
‘After completion of assembly process loader contains the instruction
using. which the location courte if set 10 the start of the newly
assembled program
1 The typical example is WATFOR.77, its ¢ FORTRAN compiler which
uses such “load and go" scheme, This loading scheme is also called as
assemble and g
er Sonate
sin meray
Fig. 0.3.1 Compllo and go losing schome‘sPaos. Hither Long,
es ee
“Advantage :Itis simple to implement. a
serge 1 Asem crocs m=O. HERE Me
Sie oS scion of jl the rues code i diety
Cenc ensue frm
ua renin pana! mning seme (lng LDIC laren) yy
tages and deaantge-
ae [EB [SPPU + Deci-48, End Sem, March-20, In Sem, Marky
tet som ne
“anc Tn is fader scheme the sce rogram’ enmvertcd Wey,
rogram ty some excl (see)
rere de wes thn ejest modules and pus machbe ining
Te aa Selon ono ir ined memory.
«The loader oceupies some portion of main memory.
‘Advantages
1. The program need not be retanslated each time while rimming it Ti
4s because intially when source program gets executed an objet
program gets generated. If program i not modified, then loader can
make use ofthis object program fo conver it to executable form,
2. There is no wastage of memory, because assembler is not paced ia
the memory, insiead of it, loader occupies some portion of the
memory. And size of loader is smaller than assembler, so more
memory is available t the user.
3. Ibis possible to write source program with multiple programs and
‘multiple languages, because the source programs are fist converted to
sn
ts mone
Fig. Q.4.1 Gonoral loader scheme
“sd fr ninering Sa
sas.
Linker ond Loaiers
‘object programs alvays, and loader acepts these object module’ to
‘convert i to executable form,
(5 What are subroutine linkages ? What are the benefits of using
a " EPISPPU: May, Marks 4)
‘Ans. + Subroutine Linkage : It is a loading scheme which makes it
possible to call and retum from subroutines.
In this mechanism the assembler pseudo-op EXTRN i followed by lst of|
symbols. These are basically the symbols which are defined externally but
feferenced in the present program.
Similarly if a symbol is defined in one program and is referenced in
‘others, then this type of symbol is preceded by pseudo-op ENTRY in the
| syibol table
}.
|
| EXTRN 5 //rubrovtine Bis defined extemally|
15.46)
BAL 115
END
‘Recomblor Linkage Psoudo-Ops
Suppose we have a main program named A and it uses variables
|ALA2,A3. which are defined in the same program then the pseudo-op
| ENTRY is sed for their declaration
‘A START
| ENTRY ALAZA
a
a
A Gale Engage3
ae
eudo-Op)
ae keno
saa lg
Se ann as Tg
ce ah re ae ng
For example
EXTRN B1B2
Here B1 and B2 are the extem symbols.
{a6 Explain : Absolute load nt
‘ans. « Absolute loader is a kind of loader in which relocated ebje,
fee are created, loader acceps these files and places them at spi
Tocatons in the memory
«This ype of loader i called absolute because no relocation infomation
{a needed; rather itis obtained ftom the programmer or assembler,
7 What is the difference between Absolute loader and Compile
and Go loader ?
‘Ans. Difference between Absolute and Compile and Go loader
Absolute loader Compile and Go teader
‘The assembled code Is place in
reloeted object files. Then loader
faccepts these files and objet code
{place at some assigned memory
lection.
‘The assembled code is directly
‘summed into the memory at sme
assigned memory location
“This echeme allows to load object
modules of msltiple programe
weten is diferent languages.
‘Tis scheme does not allow obec
rmadules of different source
program.
‘This is efficent scheme, AS In this type of loadar the
fnstruction is readline by line #8
‘object code is obtained and it is
then diretly put ito the memon
this scheme i less efficent but
simple to implement
7 Gite for Engng
|
sr40s a6
‘The drawback ofthis method ts | In this scheme its programmers
that assembler an loader occupies | duty to adjust all the inter segment
larg block of memory. Hence | addeesees and mancally do the
there isa wastage of memory. | linking sii If tal any
rmosifction fr done in some
opment then starting odes of
rent subsequent sogment change.
‘The programmer has to take cae
ofall there ieee
8 What are the advantages and disadvantages of relocating
foader ?
Ans. : Advantages
1. Using. branch instruction to comesponding. subroutine the desired
sulouine can be accessed. Thus the four finctions of leader Le
alloction, linking, relocation and loading are performed automaticaly
by the fader
2, Using relocation bits it can be identified that which instruction needs
to be relocated and which instruction needs to be erty placed,
3 Using rnafeter vector linking of external subroutines can be: done
swith the min procedue. ‘Thus taster vector of relocating loader
helps in solving the extemal references.
4. In this looder scheme, the ‘assembler provides he addtional
information such es length of entire program and length of transfer
‘estor to the leader, Using ts information allocation problem gets
ralved
Disadvantages
1) The transfer vector Hinks are useful for wansering the contol fo
Cxtrnl subroutines but this vector tale is not well-suited for leading
tr storing external data (Le. data preset in another program sepmen).
2) Dae to transfer vector, th size of object progam inthe memory ges
incresed
5) The relocating loader handles the sired procedure segments but it can
not handle the shared data segments
=Linkers end Loan
sraos
sing of Binary Symbolic ‘Subroutine(Bss)
a8 Extn 0 errr rit a
hol age moi is cime en le stoaag
: oe
fos eet oa en ot
wie eee “s
See ene
SS a 8) nk wt
See ee
Senta mere ea od
eee
gee ee
Segment independent, This information along with intersegment
references is passed on to loader.
Say
ease en
to be changed. Ifit is t be loaded in an arbitrary place in core,
7 ovjact
Feccatig program
‘Assemer iescor ‘Inter segment
‘etorenees
Fig, 09.4 Relocating load
‘+The assembler takes the source program a input this source program
‘may call some extemal routines, Hence assembler produces the object
code as an ouput slong with a table. This table contains entties ofthe
fztemal references made inthe program. This table is called teaser
For example
numbers (SUM)
SUM,
If a program refers a routine for summing up the
then transfer vestor would contain the symbolic name
Zhe sistement calling SUM would be translated into a transfer
instruction indicating the pointer to the location of the transfer vector
‘associated with SUM. ' “S *
=
A Gale for Engineering Stes
sraos
Linkers and Loaders
The assembler also provide some addtional information to the loader
‘hie inludes
Length of entice program.
+ Length of transfer vector portion.
‘The loader loads the object program and transfer vector into core. Then
it would load each subroutine identified inthe transfer vectr.
‘+The louder then place the transfer instruction to the corresponding
subroutine foreach entry in wansfer veetar. Thus execution of the Call
for SUM routine will rut in branch to the fst location in transfer
vector. Tis locaton will provide tnfer instruction to the location of
SUM.
‘The BSS loader scheme is normally used on the computers with a fixed
length direct adress nsiniction format.
(2.10 Explain the concept of transfer vestor in BSS loader
‘Ans. + + The assembler takes the source program at input, this source
program may call some external routines. Hence assembler produces the
abject code as an output along with a table. This table contains entries of |
the extemal references made in the program. This table is called transfer
For example’: If @ program refers a routine for summing up the numbers
(SUM) then irnsfer vector would contain the symbolic name SUM.
Q.11 Give the direct address instruction format for BSS loader
scheme
Ans. ¢ The BSS loader scheme is nomlly used on the computers
with fixed lenghhdigeet adress instruction format. This format
follows -
326
op | rt| x2 a
Soo
a4 g 6
‘hiss an adross of opera,
hicks dvest acsresinatucton
Fig. tt
“A One for Enginaning Stentinsmeton
2H 65386 bytes of or ‘
2 Deine the term ~ Relocation bit ie
J isuucdons i the program source need 10 be elo
tae oe ny Ben st 1 nad
SS ou eros ate, 1 ul
fen bat means comesponding address field must be relocated, of
hades eld need no be eosated
‘a3 Which information does the assembler submit 1 the dire
inking loner ?
"aus: The source program is read by assembler and assembler submiy
folonag information to loader ~
i) Tae length of promam/seqment.
iA list of symbols in the segment which may be referenced by’ ca
Segment and rlative addres of these symbols within the spment
48) lit of all the symbols not defined in the segment but refed by
coher seznents
ie) The infomation about the Tovtions of address constant, in the
segment slong withthe description of how 10 revise them,
¥) Te tamed machine code along with the assigned relative adress,
3.3 : Overlay Structure |
244 Explain overlay structure.
Ans Refer QS
SIMU :Deeot8, Mars 2)
Q45 Write short note on - Overlay structure |
cane coulion of Overlay : Overlay is part ofthe program tht is
me “other parts of the program. |
ere ee ta td
pans_of the program
Requirement’ POE can be loaded “in the memory as per the
=e
“A Guid for Engicering Sue
a0 Linkers and Loaders
‘In asemble, the overlay structure is sed in assembler,
+ Following Fig, Q15.1 represents the concept =
Ste
oS}
=m) ew
we
cmc)
(ea
_ a]
=
Fig. @.18-1 Overlay structure
is clear ftom the figure that some pans of the program can reside in
the memory simultaneously. Thus the total memory allocated is 78K
with overlay sructae whereas the memory requirement of entire
program is 152K. Thus lot of space can be saved using overlay
Ssructring,
Sle =
lee
wl
of Free
“4 ‘Space
Fig. 0.15.2 Sogments stored In the memory using overlay structure
“A Gute for Enginerng Suter3-1 Lis
gos ti
f Absolute Loader
3A: Designo!
‘ sign of about Toader with Suitable eg
{246 Give compete SIPPY Dee, Hoss
4
scheme the programmer and
tn stot Toading shen oma
Fin‘ often ein 8 IE i
ode program) consists of two
vey, object dock (bist as mal
Bren ie, omaton i present 00 190 {ype of ea
err an card and send one is transfer card et
nthe text card the are machin instructions created by aseny
Sling ih te nt () sess. Loader simply place |
[boctons nthe memory a pei absolute adresses,
+ On the eranster cad the entry point of the progam i mentioned
‘The format ofthe Text card is as given below
As
sr4os
“eR Linkers wn Loaders
+ Design of absolute loader canbe illutated by folowing flowchart ~
cum | + [2 | 30s | 6-7 | om | aw
anes [pet [com of [adsense | Empy | tseucns] ca
cau(=0 | mins ih std dia o| seq +
fa te ie ease ee ae ig he
i nh | in meme ae
se | ae byes 2
L fot) | Spice T
‘The format of Transfer card is as follows - en
eas cpars 8-72
eset 2 | as fon) n socinLoc
a t
c Daa | com=0 | Adsess of] Eapy | cud
pete ey point spe Fig. 0.16.1 Flowchart for das
as sumber -
jj 3.5 : Design of Direct Linking Loader]
When the catd is read
‘al itis stored in 80 continuous bytes in memory
‘the formats of ESD, RLD, TXT and END cards with
O47 Explai
respect to direct linking loader with suitable example.
EZ [SPPU + Hy 9, Har 6)ie,
fs aia
Mitepetas
‘ne Tene mde ae
Res. No. \. ‘given below -
[tie Relative] Object eva 2 |-
man [stat | |S 12,13, 14, 15
t
Se fy sch
; im yee, ‘subroutine (entry
eo fs
Preare useful only in the high priority pr “a 2, Waiting time : The ea
Weage period of time s process spends
an re dling it single to implement I egures «ine Pose samy day oe
sm rasan pm Se, UGS] 4 Tara tena ape
Teer Pate ae oem a
Tamarind tine =
sien melo : te + Wag tne
ive and Nowpreemptin] 4 Response tine #
in difference between preemptive and in {s the time from the submission of a re
29 Bat until the fist respoaeis eee 5 rags
5. CPU utilization : I is ee
‘sverage fimction of time during wi
processor is busy, 3 time ducing which the
i
: : 6 Rita ath ;
reamptve seeding | Noxpreemptive scheduling Doses fom te san. Al te pees
aust be given equal opporuniy to exces a
preemptive sched 1. Priority + 1 the operat
1. | Preemptive seedling allows a | Non-proemptive scheduling eas] perating system assigns protes to processes,
| process fo be interop inthe | tata proces relinquishes con| the scheduling mecbasism should. faver"the higher posnty
tr of fs execton, tsking | of the CPU oaly when it Hiss processes,
the CPU aay and allocating it | with its current CPU burst.
8. Predictabili ven process
10 another process. ity : A given process always should rm in about the
sume anus! of tine une nr ye nods
* Depeniig on te nae of operons the li
dif. The CPU ution ed nought
‘Parameters. Fairness is affect by user and system,
31 What Is CPU scheduling ? Explain 2 dierent scheduling
Fe oes no ats the design of | algorithms with example.
0 Keret
Nonpreemptve scheduling does
‘not increase the cost
Preemptive scheduling incurs 2
cost associated with acess
shaved dt,
‘Ans. : CPU scheduling : + In a multiprogramming environment, usually
Italo affects the design ofthe
operating system Kernel
more programs to be executed than could possibly be run at one ‘ime. In
Preemptive scheduling is more | Simple, but very inefficient. CPU scheduling, it switches fom one proces to another process. CPU.
complex resource management is commonly known as scheduling.
Objective of the multprogramming is to increases the CPU utzon.
CPU scheduling is one kindof fundamental operating system funtion.
User program contains combination of CPU bust cycle and UO bust
cycles. Process stats with CPU burst eye then 11 burst eyele again
Example: Round robin method,| Example ; First come first serve
1 Gale for Engncerng States
eo aaa
A Gnide for Engineering Salese su
Sg proces from the 1%) q|
Soe a Se cr
ack 5 SL ol for multiplexing proses ; ea
ae er scheduling: * FIFO is _ fir
ream ne) Sear
scheduling emaay queve. FIFO is non-preempiy
it uses a FIFO queue.
systems. FIFO is i
process contro block |
fe system, its
«When new process eaters into she from the fc
r= oor
ingress ae oad
pace
around time is unpredictable with the FIFO algorithm. Aver}
omen et ihe TOS
meee
ee ee
cite: Tet 10 ee, oo
eee ee oe
‘ear pa tuance ‘depends on the scheduling policy and whether th]
oe er a Se
2. Priority scheduling : * Priovty scheduling is preemptive ¢|
non-preemplive. Priority of the process can be defined either internally
extemally,Inerally defined priority considers the time limits, mumbe
‘open files, use of memory and use of VO devices,
* External priorities are set by using external parameter of the proces]
like importance of process, cost of process et.
‘* In this scheduling algorithm, CPU select hi igh it first.
CP selet higher proty process fis
the priority of two process is same then FCFS scheduling algorithm i
applied for solving the problem. ieialae
=.“
srtos “
‘A non-preemptive prioiy =
goes wit ‘ice
th Say ereing te, mopentaee es See
currently exesuting roses wl not change sees “Neti aoc
+ came ry ching gti wit pret A
see ricning reer! ROC Is ghey aan ce I tt
eurenty running proces, nee
Drawback of prionty scheduling
1 Waiting time is mote fo
CPU burst time is. fee
starvation problem.
lower pri
"ory process Crem if there
wy scheduling algorithma faces the
« Starvation roblem can bs saved by mag epg tech
‘In aging, the priority of the process ue
Tong time in the ready quene "Mil increase which ie waiting for
Processes |" Arrival tine | Bure ine | Peary
eee eae
Pa) @ 2
Bs z 7 3
Pinta AE SRR ae q
Ans. + Priority based (Non-preempave)
a Pe 2 Pa
5 70 67
SIF preemptive
TFs Tr
oF * ”
“A Gute for Engnerng Studentspret Sy
ce a = nt — ts re
‘Waiting me Toranrest fe inn crime aati = 2)
been fr oat Fe im E a
ma — a sa pee » La Th FP oe
" Wastng ime | rrocess] Tursaoeed ine
: | _wstet re _| re
ae SUF RR SuF RR
_ an-preamein| "| ee
ea -pecg
7 B
a ew
; +101 M457
fess Seah oe rit apm 20 eens et ae
: t(a |e alee
g+3t0+Q/4=3
+ 16+ 15+ 7/4
‘Average waiting time SIP preempriv
Average tumarousd time priority non - preemptive
Average waiting time for SIF non preemptive = (0 + 8 +9 +3)/4
aus a
Average tumarond tine SIF preemptive =(17+94142)/4" 7.25. | average wating time fr RR = (8 +749 +5)/4+ 33/4 = 938
4233 Draw Gantt chart and caleulate average turnaround time,
‘Average tumaround time for SIF non preemptive = (6 + 12+ 17 +
average waiting time for the following proceses using SIF non 2 pecans <(6 = 2212 O14
preemptive and round robin with time quantum 2. = 41/4= 1025
SPY: Oc Ed Sem, Maks 6} | Average tumaround time for RR = (14-411 +17 + 13)/4
Sm =sis= 035
free ete a Era tive 136 What is preemptive scheduling ? Consider following example
7 a é and supply round robin scheduling policy and calculate average
Ps 7 7 ‘Turnaround (TT) Time. (consider time slice = 1).
% 7 A (SPP: Dec, Ed Sem, Maks 6
Fi 3 3 Process 1D | Arrival ime | Serve time
+ SIF Non -premeptive : Gant cha [a a 3
z 2 é
Fin Py c + 4
g so ca D é 5
21
E @ 2
“Gwe Essien Sade
“A Gn for EngnsrngSdetsSPOS : 4-33 Operating Syste
Ans. : Gantt chart for Round Robin (Time slice = 1)
Aja |e Ja ye Je Je Te fo fe le le jeje ye le 2 pP
OE ee eee a
tr
Precess ID Waiting time Turnaround tim,
A 1 4
10 16
esl
ufo]
s
a
cS
Average turnaround time = SeleH ss = 10.6
END...2‘u
Synchronization
and Concurrency Control
5.1 Concurrency
Q.1 Explain the principle of concurrency,
Auns.: © Concurrent access to shared data may result in data
inconsistency. Maintaining data consistency requires mechanisms to ensure
the orderly execution of cooperating processes. .
© Concurrency arises in the same way at different levels of execution
streams. Following are the example of concurrency in different types of
operating systems :
1. Concurrenrrency in multiprogramming : An interaction between
multiple processes running on one CPU.
2. Concucy in multithreading: An interaction between multiple
threads running in one process.
3. Concurrency in multiprocessors : An interaction between multiple
CPUs running muitiple processes or threads.
4. Concurrency in multi-computers: An interaction between
multiple computers running distributed processes or threads.
¢ Java is a concurrent programming language.
© Process synchronization is required in uni-processor system,
multiprocessor system and network. If more than one thread exists ina
system at the same time, then the threads are said to-be ‘concurrent.
Synchronization problems can occur whenever two or more concurrent
processes use any shared resource.
* Cooperating process share the logical address space.
Is concurrency is possible without parallelism ?
° Yes, concurrency is possible without parallelism.a
aos $2 _Synchromtation and CONCHITENEY Con
than one process or thread i9 Progressin
‘it does not imply that the TOCESSCS ap
allows for eoncureney
‘with more than on:
i ame
dees meas fe
Sein nome
ee er
ae
canon 7
) Criteat section H) Race condition
Fig. 0.21 Gritcal section
* Critieal section means, process may change some common variable,
writing files, updating memory location, updating a process table cts
When process is accessing shared modifiable dat, it fs said to bei
‘Each process takes permission from operating system to enter into the
critical section. Structure of proses ie as follows +
1, Entry setion
2, Remainder ection
3. But section.
‘+ Entry section: 11 is block of code executed in preparation for entering
‘+ Exit setion : The code executed wpon leaving the ettcal sec
« Remainder section: Rest ofthe code is remainder section,
<= =<
sr408 Se
ate et orang a
* Each process cycles though remainder, entry, erica, exit sections in
si) Race Condition :
Race condion cei shen two or more operons crit in aa
sti mam Whey ome pores eng wag
shen, ar eed race condones 7 MH HS ly
+ Ph ae codon” ems deeds th tof he
“interleaving” of the threads. ria Neen ee ee
+ Race conn should te avoided tease they can ase See fn
applications and are difficult to debug, 54
41m banking ssom balance i» shard vibe
unt, ope by bank tnployee
Balance = Balance + Amount
At the same time, some amount is transfer then it becomes
Balance = Balance Amouat.
These two lav Ins ne we vale tlc. i
sro Ot nt tt eal eof
+The exoares etoon of prs mt gummed 10 te
Etomidate creo hr ae pf a
Samay nt pore sane et
23 tapi the flying tras
1 con ein) Spcronietion
dhs 1) Mutual xcaion + Mona! exclain mets we wed a
cocaveat popenning bold in Stone ef Soon
scour ass Ba yr by prof compas cx ele
te dom,
S"Requemen of muta exchsion i, wen posi PL sein
eRe’ ihn eer rr ube abl se
aaa cresal pes Pl hm fase! kr apn ih owes
Pe
+ Bumpls of ssh seme ne
sale onto ean ce
eireintonSyoneton mes trig stem ous
Oe yh nen sco Sel dat de
Joc ninig te coc onsen et
‘After depositing the
VO devices such as printersBe,
G4 List the requirements of mutual exclusion.
[pry Mey tt, Dres?>
‘Aas. : Requirements of mutusl exclusion
"As any time, only one process is allowed to et
‘Solution is implememed purely in software 0” #
[A process remains imide ts critical section for #
No assumption can be made about relative sets ©
‘concern PrOCESSES
5. A process camnct prevent any otber
section
16. A process must not be indefinitely postponed fom em
‘section
nd Sem, Marks 5)
machine.
‘pounded time only,
pepe
$2: Mutual Exclusion :
Hardware and Software Approach
{5 How livelock situation is avaolded by using Dekker’s sotution ?
‘Ans. + + Dekker’ solution avoids « livelock snation
pekkers algorithm sas the fist correct soliton to the etic section
problem for two processesthresds. It uses an amy of Boolean values
Sand an integer varsble
1s Dekkers algorithm is purely software solution with no special purp
hardware instruction, I uses Dag to indicate a process desire to enter
ial section
4 If two processes try 10 coer their cra sections atthe same time
‘variable "um indicates which of the proceses should be allowed t
Be anv ale mens sae
‘using only shared memory for communication, nie
Fe en ees a
ree my oe ig a ig
i inte ettcal section
sf asynelronous
process for entering into critical
ering its exten
1 Here, if PI finds <2 = 0, i defers to P2 only if tum =
simply silts for €2 to become I before entng it ential section,
+ Process P2, which is also eying 12
ime, is forced to defer to PL only if sm = I
‘Dekker'salgortim is corect and it satstes mutal exclusion and
itis fe from deadlock and sarvatien
Limitation of Dekkers Algorithm
Dekker’ algoritim des not provide tet akemation,
Dekke’salgoritan wil aot work with many moders CPUS.
This algorithm wont work on Symmetric Muli-Processors (SMP)
cpus.
4. Additionally, Dekkers algorithm can fll regardless of platform due
to many optimizing compilers. Compller may remove writs 10 fag
since never accessed in Joop. Creating an innit 100,
0.6 Write short note on : Peterson's solution
‘Ams, ¢'+ Peterson's solution is software based solution for ert section
problem, This algorithm will nt work coresty on the modem computer
Urchitccture, Tei simpler algorithm for two process mum exctusion with
busy writing, :
om atthe same
1
2
3ssiaes ge Syncroizaton end Concurrency Coy
217 loot ists complied than Dekker’ algorithm.
Reson algo solves ciel section probit of 10 proce,
iy. does not require any special hardware, TWO POEeSSes alten
xscution between tir crcl seton and remainder sctons,
*EGTRSK hd indesne possponenent are impossible in. Petey
jv long as no processor dead frites unexpectedly,"
* For indefinite posponement 10 ecu
2c 0 contimally compete ode
ther proces bisy wate,
7 Explain inter
ABS. + On a
Possible Batt
ics sulin
cone proces would have to
ne risa section ‘while
>t alsabling concept of mutual exclusion,
irocessor system, parallel execution of process is
coe onl be inctlesved. To gurantee mutual excuse
"9 Prevent a process from bring intemupted. P
ee Behe
Fiona
$A process can pe
© vent the operating
issuing any supervisor rie
+ Use interupis,
8) Implement
»
©) Inroduce uninterruptible code regions
¥) Think sequentially most ofthe ime
©) Delay handting of external events
‘Econ
ag
| pjsadvantages
Ii was on in he mee rong
2, ier ca lint end pr
4. A process waiting to ener a
em ‘to tc cnt eg
a Wat ae the sdvntgs and g
aT brn of tot aad a
‘Advantage
1. Simple to implement
2, Ieworta well fora small mine of pcs
3, Ikea be used to suppor mute eri sean,
Drawbacks :
1. If suffers from starvation.
2, There is posibilty of busy wsitng
3. There may be deadlock.
G9 Explain with definition, the concept of general and binary
semaphore,
‘Ans. + Concept of general semaphore :
* Semaphore is described by Dist Semaphore is a noaneatve integer
variable that is used as a fag. Semaphore is an opemtng sysea
atbstract datatype. I takes only integer value Its wed to solve erica
Section problem,
* Dijkstra introduced two operons (P and V) to operate on semaphore
to ‘solve process synchronization problem. A proces cally the P
fpemtion when it anis to exerts eal seeion and el V
‘operation when it wants to exit it titel sion. The P operation is
called as wait operation and V operation is called as signal operon,
A wait operation on a semaphore decease its vale by one
waits : while $ <0
ao opeSAE EE secre at concen ret
4, Merits eect
Rly Se ata se ee ‘
ie ‘ey ac sor sana gper p
soar dex i ace iy we Ss SUEY. Ba eg
‘nee oe te pt oy sg # 3 met. Sn Ce
Soca os Se pt 57 HO eater aries
once Seite fer meng to om ee
& mnie sax sco sip ee vaste Ser ealy
yostcs ts late
Ph canibon sarily
tera (contin vate
cM eel pi on a condition varisble automatically does an up on the
in ot 9 poor an ‘monitor and blocks the calle,
8 Wied sey ewait on
Be ms tr tgs 4 5.5 : Reader Writer Problem
146 Last the Arewtwed. of . q
ysl pefvvhcstoeahebemea 0.46 spain reader writer problem. a
a wat mae tn Aout» When'o peso psc ss ses al es
[ihin x eon a tne ine only one posers ag AY HT a such as a file or database, They called these processes reader and q
Is the possibility of deadlocks int = satiate
als I C886 Of es cae * Multiple readers ean coneurenly read from the data base, But when
2 Spiatng the qc, sas enly eon we ice et
sie anno ede te) =
* More than one reader may read shared data (no weiter). When @
ses shared data, all other writers and readers must be excluded,
Geos “A Guide for Engineering Stdents=
coer
SM = a
net
vi 16 os ae Pt
@~
&
ron
Pe Rad Se
symm en a i
"net eon Tepe led ee Pe EE do
Sogo te ee a lane ho any
Sse ee Tce We de an al ion shang
=
“Re Noes a the ming raison pea i
Wer tn mad te dans ar mca ares
+ When writer is active, no other readers or writes may be active,
Therefore, st must ea
free muta exeusion if tee ae groups of
readers and @ er,
* Reader writer problem is snilar
smong a set of processes. po
may shice the Ale with any othe
fle
'o one which a fle i t0 be shared
ces wantonly to ead the fil, then it
proces that also wants 10 read the
* We apply rules for access order
Lia writer is
more readers,
tn fer ders 0 be fied ont stow any
2. a reader is waiting for writer
4 JF the writer wants to append the
0 ftsh, he reader pray
have acess Yo the file when ihe wi
Sis, then no otter
ers aes i! PO ould
* irae having higher pricy than the wie ty
arvaton with writers, For wre he
Sher yi
ving higher priory gg tll be
then starvation with readers, er ory ta eae
47 Write a semaphore solution for readers - writers rotten
* When two wypes of process need to
88 0 file oF database,
such
0 shoe
They called these procesey et ecg
dey
nd
‘witers may be active, Therefore, it
must enforee mutual exchsion if there are groups of readeo nd
serie
«Reader writer problem is similer to one which a file isto be shared
among. set of processes. If a process want nly to read the file, then it
may share the fle with any other process that alo wants to read the
file, If the writer wants to append the file, then no ether groves should
Ihave access tothe file when the writer has access toi
Mf) reader;
1 assume multiple instances
so verter:
17 assume multiple instances
jwoid reader )
© whoa)
{
wate
readcount ++
wold wt) {
Dw) ¢
waive)
aowting
toneading signalweem)
waite pay
roadcount >
fk readcount:
sigual(waer);
signplix,
}gmt COHEN Cony
see ee en]
[rr cme Poe
56 : Producer Cons
et problem sing
37, In Sm, Marks 6)
x ee er
rags fem by using bing
Ans: Solon to prodoesr consumer bl ry
Semaphore
oid main ()
pensions
{nt consumer ()
me
FemWaita(detey),
le re)
semsignal(e
conmumedata
Wp==0)
sen
}
joa Ft Synchronization nd Cncureney Control
J What is clea section? Give semaphore
ot oamer problem,
Intion for producer
vee A erdeal settion i a blk of cade that only one process at a
{ime cam exeeute; #0, When one process isin its real Section, ne other
process may be in its eral section, The erica section problem 10
Epgure that only ONE process ata time is allowed to be opcating in iy
‘atial section
‘Producer consumer problem “is example cassie problems of
synchronization. Producer process produce data item th, consumer
process consumes ater.
‘Buller is used between producer and consumer. Buller size may be
fixed ot variable. The produce portion ofthe application generates data
and stores it in a buffer and the consumer reads data ftom the buff.
+ In order to synchronize these processes, both procedure and ‘consumer
are. blocked on some condition. The producer is blocked when the
butter is fll and the consumer is blocked when the buffer is empty
4. Code for producer 2, Code for consuiner process
|S ome |
eocuer i [ensues it
i I
tn |" ecto
we HU) ‘a UB)
t t
produce tes (ta secu ==)
rece tec tun
secre tm (tm
slaep (i
enter itom (tem)
counter = countsr + t)
i (counter = = 1)
‘wakeup (consumer);
if (count = = N=1)
veakeup (producerh
‘consume jtom (tem):Somcontaton and
‘sraos sn : Cenenrenee
“3.7 : Dining Philosopher Problem
20 Write semaphore solution for dinning Philosophers proj,
SFSU D749 4 Som, sg
‘Ans. : There isone semaphore for each chopstick: 10 addition,
two-phase pritation scheme is weds mder which philosophers ger
thee mighors who have declared themselves "hungry." AI arith
module 5
‘yetom DINING_ PHILOSOPHERS
van
Me: semaphorn, nial t; for mutual axehseon */
15k. semaphore e(, nin © 1 for synehrenteston */
fgl6l (THINK, HUNGRY, EAT, inilly THINK:
1 pilosophor fag */
1 he before enc ps
Ae beter, ench pitccopbor i on endlogs cyto of thinking and
wr)
F °
lake. cropesicet
Enming,
,
)
110 sobs eesti
hci
‘ion going on so Rae
procedure take
(
Dowty,
aoa
2= HUNORY; pene
a
59 Seine ee
‘ypten0d: 1 ond erica ssction */
4 ¢phagtt| == HUNGRY
8 pflagil-t] b= EAT
‘ae pllagil+ 1] = BAT)
thon
t
pflagisl = BAT
‘uP(ett)
}
)
11 Once « philosophor fnishos eating, al th: main eto elias
thw ronourcon, Ke to chopsticks and teraby rlansa wating
nolboss.
void drop_chopatcketine 8)
{
DOWN(me), ——/* een! section */
oat), 7 Lot pl. on lft eat if posible
ot) 7 Lot pl on eg oat if possible */
P(e} 1° wp exinl soction 1
>
2.24 Fxplain caslenl problem of synchronization in terms. of
it Philosopher problem, £9 (PPV: Hy, End Sm, ks 51
Ans. + Dining philosophers problem one of
lasial process
Tiere lve philosophers are seated. around &
hoking and cating. Five plates
nehronization problem.
creular table. They spend thee lies in 0
with ive forks are kept on the creular table
+ ve hsp nk hy oe,
Tar Where olson desde o ex then hee must oii 4
fon, one a Teh side fond note fom et ie
shoot pep ol a ingle to HE: SSS
“a erieyeni and Coney,
replace the for and
Afr consuming fd the pisos Te18 E, TE 6 ey
| Sa ms whe ok oo, SIE Py
{ ‘eanaot eat while the dinning philosophers 15 ate
‘ed rou.
ve philosophers
‘Fig. Q21.1 shows seating amangnent of five philoso
seas st
2214 Dinning philosophers
+ Ga
der the following code
oid inning Palosoper () |
te rue)
eid ating ()
4
takolehtor ¢
‘honigtone ¢
esticeddlay)
atsighttore (,
Putettoce (
}
oe Svechronestion end Concurency Cone!
ce
i (an es wpe Gs
He ee a ot mcr 4
it This isnot possible because ofthe fellowieg i
= Ee} +e
l ze}
Fig, 0.24.2 Philosopher states
‘Each philosopher will hold exactly one fork, and 20
available on the table. The philosophers will ll deadlock,
To solve this problem, write some extra code in takerightfork (-)
procedure, User can specify the philosophers to put down the lel fork
if that philosophers cannot obtain the right fork.
Problem analysis
# Shaved resource : Here each fork i shared by two philosophers so we
called i is a shared resource,
will remain
+ Race condition We do not want philosopher to pick up «fork that
hha already been picked up by his neighbor. Ths isa race condition.
* Solution + We consider each fork as a shared item and protected by
mutex lock, Before eating, each philosopher fist lock lef fork and then
right fork. If philosopher scquires both locks sucessful, then
philosophers have two locks (ovo fork) so he ean eat a fod, Aer
finishes'easting, this philosopher releases both for, and thinks
Some other alternatives
1. Pick up the left fork, ifthe right fork isnot available fora given time,
put the Jet fork down, wait and try again. Even if each philosopher
‘waits different random time, an unlucky pilosopher may starve.
2. Requie all philosophers to acquire a binary semaphore before picking
‘up any forks. This guarantees that no philosopher staves but limits
parallelism damatialy
“ie for Eaierng SesP|
sre0s se Src cy,
pstik, cach cho
‘Because we need to lok and unlock a chopstick, tig
fot ct ines, ead 0 cat fe ted op
ich philosopher. Since each philosopher must have access tq the tye
=e Sanit saa annees
IMMes locks ae global vale,
5.8 : Deadlocks ; Principle of Deadlock
4s deadlock 9
2.22 Whar ‘State and explain the conditions fy,
aeadtock, PIS: Ma nd Sem, Hs
OR What are
‘necessary conditions for deadlock ? Explain the
cae eadlock ? Explain them with
STP: be, Ed Sem, rs 4)
pre Desilock can be dtd asthe manent blocking of
Processes that, +r: Day
Om sharale essary Pfr ste resus. Dealoek ea ecu
TA process is in
ae ceca Sa Ht ms wating for «penal event
aan Sem dae, ono mae pretest
* Following four conditions ae neces
2 Mata excision 2 Ho ag vat
a for deadlock to exis,
3. No preemption
1. Mutual exch
One process at atime
2 Hold and visit +
ranted cartier
4. Citeular wait
TesouCe may be acquired ‘rehasively by only
ty ay HES ye
3 No preemption +o
cannot. remove jg aa
Som the pce conta. A te system
finished using the resounee se ws es ar
4 Glreular wait: A circular ein g
Grr nO ld a ing eit in
All four of these
otis ms be pre fo «ye
Occur. If one Of them i “abser 7 ie
4 no source dei
deg
ong
‘Mince
‘i 8 it inde
¥ 1 A (oct may Vat indefnitly teense aber proces
o srr gin and geting the requested
‘koe
Tesources before tis process
s.
Sitch lin, mes & i invol
Fa fe ropes. Ina starvation siuation 4
sats mt being allowed exeeae
‘q24 Write short notes on :
‘Resource allocation graph and resource
ssiocation graph algorithm,
Fig, 264 Process
Bal
lu eoa|
Fig, 242 Revourse
“sh 8 instances.
etal re base
invine of te x has been allocated fo the proc ‘
+ Regus ig coed a some ln HS
allocated (othe process. When
Smet lp econ i
oo
rtre
_sycronition and COUCH Coy, 5-35 Ssctroieion
Secon ET Coty nd Concerncy Conta
sags st
j vlsey_ ns F SMES OEE Ry tl eg
| Acie SSE OEE Rs wren roe ee onired oe
@==GEs | pesto
(6) Claim edge
lope a osu 1 lease by Fhe aint sige 8 i
(a) Request
" cried to a claim edge P; +R.
con"
ues can be granted only if converting the
Pai ng the request ge to an
eat edge does not result in the formation ‘fs ce ie
ae location graph. re
ig, 0243 Edges
0.244 shows «resource allocation graph. SYSIEM consis. gy
5.9 : Deadlock Prevention
28 Explain deadlock prevention techniques with example,
ISU ay 6, En Sam, 5)
‘ans: © To prevent a deadlock, the OS must eliminate one ofthe four
recessary conditions
TeMutual exclusion 2. Hold and wait
[Link] preemption 4. Circular wat
1, Mutual exclusion = It is necessary in any computer system becuse
some resources (memory, CPU) must be exclusively aloested to one
ser st a time, No other process can we = resource while i is
ces sp, p, TOMA Rte tector gph | atocsted to process.
Re es 2. Hold and walt If a proces holding eorain resources is dened
rae RRs further request, i must release its original resources and if requied
Resouree allocation graph stgorithm + ee
orally requst ede and assignment sage je yee alsaon. graph, | 3. No. preemption : It could be bypassed by allowing the operating
In addon 10 the request and s system to dallocate resources fom proces.
ssignment ee, new ede called aay 4. Cirewlar wait ¢ Circular wait can be bypassed ifthe oprtng system
on ete is added, Foe “SUID prevents the formation ofa eile
Sram cali eg
indeer tht proces 9
rete rue fone tg
inte we, “tie
vm doe esi
Bae. Pig 0.045 ae
idk svete vith eg
‘sllocation graph, a)
+A. deadlock is possible only if all four of hese conditions
‘simultaneously holdin the sytem. :
+ Prevention straegies ensure that at least one ofthe conditions is always
false
28 How can the hold-and wale condition be prevented ?
‘Ans. + To prevent holé-and wait condition, prooeses must be prevented
fiom holding one or more resources while sinullnesesly wating for one
for more others.
=S_—.sra0s.
Thc ae seer pss fr thi
1 Regi taal proses request al SORES atone ting
Ferma of sem Tens 4 CESS needs yg My)
enly ints exeoton and doesnt ned some other reg)
che ~
2. Regue that cet Blig rescures must release i
ee ee ae ae
Along wh he nw ones in 2 single NEW TqUEL, This CH
protlen if eros hs pri completed an operating
"sare an then flo gt it relocated afer releasing i, "4
‘Bier of the methods decried above can lead to sarvayj
Foss ees on moe ppl eu io
0 : Deadlock Avoidance
te adic ie it abe xg
z
OR Write Banker's
‘etre ad expuin with suitable example
TIS: beet, End Sem, Mas
OR Write and ex
lal Denker lpr forevidance of deadlace
Abe: tr
c/n ite
is ened bese de tn ane ae A,
a. = me ‘modeled after banker who ‘ae
; "she pom tae med
Algriin is eek a
se it
‘state, If it does, the rec Save
see fe de ig ens an
. Tes lads
+The Dist
a proposed an algorit
tid desde The ba
avoidance method, "
* By using avoidance m
peer ries rt em ta ey
dase) reck if @ deadlock is created Sah sa
analysis method is used for th » Sri
hs. be a reques
‘
ra
et tM saan
known of the
st Syehrenzon en Conary Cot
ps0 3
cnte «These 1a stone Sec of resus
1 st et des ot result in a dalek.
a safe state only if there exist a safe sequence. A safe
sem i ce. A safe state
psa site an ona Se. dos mem te ten in 2
locations to
deadlock.
«ps ong 8 the state Safe, te resource marae cn be gaat 0
void 8 deadlock
lly the system i in a safe state, When process equests resource
hat resource is available then the system must decide whether the
or process must wai
allocting resource then only OS
i
and t
fesources can be allocated immedi
‘eae system remains in safe state a
allocates tesourees 10 Protss.
a Banker algoritim uses following dat sucrures,
4 Allocation : Allocation isa tbl in which row represents process and
column represents resources (R)
allo {i j] = Number of unit of re
sae Ry hed by process Py
[Link]: Max be the maximum number of resources that posts
requires during its execution
‘Need (claim) + It is curet
js equal to its maximum need minus is
Need = Max ~ Allocation
‘Available: There will be sumber of ©
ftocaion. This is equivalent tothe total cumber of
Sham of the allocation 1 all processes inthe sytem,
‘Number of resourses ~ Sum ofthe allocation
Jaim of a proses, where process's cai
‘current allocation.
sources sill available for
resources minus the
punter ores - Alon)
th total number of resource in
fat once alloested &
more that
‘aust also guarantee
That resource to the sytem within &
«Each process cannot rues
the system. Bash process
resource the process il
nie ime,
* Deadlock: avoidance
Fon eg ianee wes the worst-case anal
adc M8 ey
os "0 check for.
Gone 3