Download as pdf
Download as pdf
You are on page 1of 48
unit ~ i ag Deacl loclsg- | A deaclock vs dhe situation whore a proess tends to wait indefinitely for a resoure held by ether waiting processes. | Deol Lock can be ocwis on shareable resources Ube Files prinbers, clisks, database, seannor, memory ete. prinker halel | yA system consists of a Finke number of resources | tp be alistributecl. among a number of competing prowsses. 4 The resoures may be pentitionaat ‘to several types, each consisting oP gome umber of identical instances. een Moelels - & Memory spate’ epu cycles printer, scannl, Gye examples ef yesoune types. * ® process may ulllize yeseure, in the following Sepuonte © sequeds a The process yeguosts dhe Yesoure. aP dho Yesuost cannot be granted Immuclately chan dhe reusing | ibe Process must cuit until 11 ean eeait gepwire dhe yesoure | “The process can operate en dhe esourt.(eg:- IP dha | jesoure (8 @ printer, dhe provess can print on dha Printer, @ Release: | The process yeleases the yesource . ‘dead Lock Characterization: | The vayiows chayacteviration Reatures dhat. describe a deavlloce are, an) | © Necessary conelttions:- A deadlock situation can arise iF dhe fotlowing fur conditions ola simultaneouslyin dhe systems. 3 mutual escclusion:- Atleast ene yesoure must be th nonshayable mode. that 18 only one process at a time can Use dhe yesoure. fy other process yequesting i for i} must wart. 4 Yold_and_ wall: \ A, process yequosting yesources Weld by | another protess. must hold atleast one resource. Te Resour cannot be preempted. dhat i's a iesourn can be Yeleasect only Voluntarily by dhe process holding it, after chat process has completed tts bask. @ oculay watb:- A set of weuting protesses f po, pr..-- Pri} must exists such dhat Po is waiting Ry aie held by PL A is waiting fey yesours hele by Pr. Pray 18 wating for yesoura hele by Pn andl Po is waiting for dhe yesource hele by po- © Resource allocation graph: a Tre — Bystem allocation graph 1s a direetedl graph consisting of a set of verhtes v and set of a Tre set oP achve processes 18 given by P= En PasPl} and set of vesource types given by R=2R,m2... am % The processes are repre senbea as cide, # Gach ‘nstance of dhe resoure type ts veptesented as dot within dw square. | * The edges connecting vertees are also two types, by teguat edge 4s assignment edge x Tre Resources are ‘representeal by squove. | i | | ls A yepuut edge is a aureckecl edge ‘Connecting @ process Pi B& yYesource types ty and v's denoted by Pr> Ri Cee vs waiting fey yesoune Ri, a aD asaign monk edge 's the. cliyected edge connecting a yesoure type Rj bo & process Pi and 1's denobecl by Ry > PC Cry ts allobbecl to process pi, Rg “~ The yesoure alllocating graph clescribes dha Fertousing sibuation. +P = Fp, Pa, Pa} SRE ER, Ra, Ry Rog E= Zp, PrOR3 RiP Pr, Ri PL Rr Pe, 3 PHF Resourw_Lutanus:- % one tnbane of yesoure type Rj * two tutante oF yesoure type Re * ene dutane oP yesoure type R3 * Thee insbane of Yesoure type Ry, Process sbabes:- ¥ prowess pi is holding an uubane oP yesourw type Ra anal ts waiting fer an instante Of yesoure type Ri x proess pe 1s holeking an tulene ef Yesoune type band Re and vs waiting for an Instance ef resoure type Ra. A process P3 ts holeting dro tulane of Rs. Cuiven dhe defintion eBa sesoure allocation graph 14 can be shown dhat rP dhe graph Contains no Cycles, than ne process Cn dhe system is deadl locked. IF dhe §raph dow contain a cycle, dren eleadl lock can occuyedl. | In dhe Given Yesousw allotation graph suppose Ghat process Pa reguats an instore of tesoure Iypere, Sine no Yesoune instance v's curently available, we adel & | © ho A dh int 4wo requed edge PPR fo dhe gia! Pe minimal cycles eaisbs | PDR Pr 3 P39 Ra Pr, —>R3—> Ps—d Rr—> Pe. Pro k3 a pi pe and ps ate Aeadlocked. proess pe 1s waiting fr dhe tesouxe Rs, whieh is hale by Process p3. process pa ts waiting for efther Ploess pir oF Plocess pz tp yelease Yesourw Br. In Addliion process pi IS Waiting foi process px to release yesoure Ri. j Now consider dha yesoune allocation graph , Wwe also have a cycle bul no deadlock. fig- Yesourw allocation graph with — dleaol Loe Fa: no. cea We wit Cycle. ProRi>Ps Rasp, diagram Py may release dutene of yescurw type Rr. Thon dhat yesoure can be Jn te above Tbs Allocated to process ps, fy breaking dhe cycle. | | ros aiid | << ne ées i | | | | Methoels fs HeunelLing Dew oer: | we con dleal with dhe cleat lock problem cn ore of dee ways & Deadlloce preven ton & leant locke avoidante method to prevent dhs system from entering dead lok stabe. | % Deaol Loe alebechon and Reeovery. » We Can Ygnore dhe problem complebely and pretencl dhat cleac Loe ever oceat iin dhe system. | The dure © solution’ 1s dhe one ued by (mast eperahing systems cnelucding Linux and unix.and windows, Dead Loels. prevention: Lusion:— | ® Wutual_ecd ‘ Gost ome Yesourw must be in yon Sheyable mode. | * Only one process ata a tm can we dhe Yesoune. | > Real only Fler are bess example Ra shavable resource, ap several Prowsses attemp} fo open a head only File at dm same tims, Jay enn be granteal Simultansen aes to dhe fle. Aw Process raver neecls to wait Ri a shavable Yesource- ® Hold ancl_waik:- » The hold anol wart condition novey occurs P when a Process repuest dhe tesouwe, 1 does not hotel any other Yesoutces, | Thd can be achieves by using one oP dha feitewing two protocols. O Hil resources required by dhe prowess is atloeadctel Allocatect at dha beginning of dha execution ise. eq: “lebs bake dhe copying lata Fforo dhe lope arive to alist sox dha dish Fle ant Prin’ dha tesutk. ® Ensue dhe process can eguast for Yesoures only when N& dow not hold any otha yesources. eg: 8 The process Fist “tequast for bape drive and disk Fite By Copying: after Finishing dus Fast i& yeleases dhose resourtes and again yequart for disk file xno printer ion printing. elisadlvantages :- YD Resoure utration is low. 3) possibility of stovatlon. © No preemption: apa prowess Pr ts using a resoww and a ‘hugh prionty Process pz Yeg uats fox dhe YesourW, Pyocess Tr ts Stoppeel ana dha tesources ave allocabecl bo Pe. | | Pa provess \s holeling Some tesources | jana waiting for olhor yesourtes , dhen ib Shoulel telease al) breviowly holed yesountes anol pat a now request for dhe Neguireol Yesourees qgain. | Pe af a process has Yesoure Wi,R2 ane R3 and is uwaitig fey yesourm 4 dhen 1) i to release pre andl Ra ‘and put a new ‘reguast for dhe At ited Yesounes again, yeutor waib:- & Each yesoure will be assiqneal with @ numerical number. | af Protess com yequat dhe yesourws LneteasingHeereasing order ef numbering. jar oof Pi provess ts allocabecl Rs Yesources now nest Hm (P p ak for Ri, Rs lesser dhan Rs sue request wall not be guantec, only veguet for Yesoures move dhan Rs will be granted. To utolabe dha aiveuler warl we can assign @ prionty number bo each ef dhe, resource. 9 flocess canb Nequest fy a lesser priority iesoure. This | ensure dhak a Single process Can Nequass @ resoure eahieh ts being at util'zecl hy some other Proess ancl No cyele ewill be formwel- t | Deadloels Avoiclance :- _————— In lead lock avoidance dhe request By any Nesouve evill be granbed P dhe yesuning state eP tha system Lies nob cawe cleadlock in dhe sysbem- The state of dhe System aill Continuouly be cheeledl fox x Unsafe and a safe sabes, | sak shater | JP dha system can allocate’ esoures tp each jprocess dh some order and avoid a deadlock. n system ts kn sa stake only \P dhore encists @ safe sequence. Consicler dhe system with twelve magnetic bape dyives Gna dren processes po, Pi andl Pa. aoe Po requites ten bape Arives process pr May reed as 4 tape dmives , process Pe may Mee ¢ tape elnives. Suppose at Hime mrotess po > hold S$ tape Arives, pio Wold @ bape clnives. Pr—> hold 2 bape drives. Maximum __Heeel eomeni_ needs Po to 2 pr 4 * Pa. 4 & i| AL time to, dhe system is in safe state. (The Sepuenie satisfies dhe safety condition. [piocess pr can Immectvately be allecatecl to all th tape ldnives end dhen Yelumn. now dha system have Five (312) iavailable bape alnives. The process po den get all ts bape drives lanal yetun dham. now dhe system contains to (545) available lee drives. Rnaily Process Pa can geb all is bape drives land yetum dem. new dhe Sysbern conlains 12(\0+2) tape ldrives available. | unsafe _ states. A system can ge ffom a sae stake to unsaR state. Suppose ab bime by, Process Pe reguoss and 18 allocated ene more tape drive . The system 1's no Venger in @ safe state. ' At dhs Point provess py enly can be allocabed U Ves bape dbrives. When 1% tetuyns dhem, dhe system will have only Bai available bape oltives. 8inwe Process po us Alto cabeot Rive tape elrives bul hos a inoximum of ben, te moy ‘Yep uoat fice more bape dmives. aP i+ doe so i} till warb, beeawe dhey ere unavailable. similarly prow Pr Roxy reguas dix additional tape elrives ano have to coeu', esting t a deaol Loele. Resour location coraph Agari: | | f ie In asllition to dhe tesoune yeyuat edge eal Assignment edge , we tntoclue @ new Aype of edge ‘s ot as claim eolge.. A claim edge pp > Ry Unebicates Jhad process Pi May Yepuest tesourwe Rj at Some time in the fature. Tha edge resembles @ Yepuat edge in duvection bul 1's yepresented in dhe geoph by @ dashed Line. | when process Pr yegust yesoure Ry, the claim edge pr Rj vs Converbecl bo a Yepuest edge. similarly whan a yesoune @j (s veleasedl ky PL, che assgoment edge (Pr ts convertect to a claim edge Pr aj. Re ch Suppose dhat Process Pr yeguests .y Nesours Rj- Te Yeuast can be granted only iP converting the vezusb edge Pi Rj b an assignment edge Rj > Pi does not Result in dhe formation oF dhe eye tn dhe Yesourte allocation Giaph. we chek for safety hy using a eycle clebection algorithm, ¥in algorithm fox elebeching a eye to this sreph Tue An order of nt operations, where nu che amber ©P prowsses do dha system. Garkess Agathe The yesoure allocation geaph algorrthen 1s nob Applicerble to a vesouie allocation graph- system wrt Multiple instances of cach resoura +P. The aleaol Locte Avoielanw algorithen that we describe pot applicable Us tho banicers algovithm. for example, suppose dhe number oP auounk holders th a particular bank 5 ‘»’ and total monoy un a bank ist” 3P an amount holder applies fora loan, frst dhe bank swohath dho loan amount foro oho Fat cash anal thon estimabes dha cash diffeienw is greater dhan 7 to approve dhe Loan amount. Similarly 1 worss cy an Operating system. whan a New process is createcl cn a Computer system , tho Process must provide all types oP énfermahion to dhe eperating system Lee upeomitg processes equa for dhely resources, counting dtm anol clelays. Baseal on dhase eriteria, the @perating gystem ecides whieh Process Seguene shoulol be execubecl ey Waited So dhab Yio oleadlock onus ina system. Te Bottowing ae dhe ‘important Aata structures berma—useot tn bankers algorithm. n ts dhs number of Piocesses anh m i's dha number of each type oP rescue tuea do tompulet ayshen. ‘ sunilab is an anew OP length m dhat clo Pray each type of Yesoure available tn dha eysem. If available Cj = &, ten lw Instn of yesourw type & ts available, 4. Max t- Yo nx matrix olefins dhe protess pciy can stove dhe maximum nurnber of resourw x} in cho system. 3. Allocation:- Yo nam matrix de Ares he number of Yesources of €oeh time curently allocabedl to eath Process. 4. Need:- s. Ru id Jt is dho vector oP dhe erdet m. 34 (ndudes bedeen Value bru ot False, inciting odhethor dhs ess hos been Allocakect to dhe “tequated resources, anol Ul Yesourcer have been released aPtey Fishieg Yb baste, The bankers algorithm is dhe combination of dhe safety algorithm anol dha tesoune Yegusit algoriti bo contol dha processes and anor alead love iy 9 System. Safely algo: | The safety algorithm 's for Finding out whothoy or nob a system Is th a safe state. Th, algorithm carn be Aeseribed as | 1. Leb work and Finish be vectors of lenge m and a, Witlalre work = available 4 Rinish cia = false for U=01,2,.-.n61, 2. chee avaulability status ef each type of yesounw cis theo «) wed cis wore diy Gish Ud= false UP wo sutb ¢ extsh ger step 4 3. work = work+ allocation Finish oi3= hue then goto step 2. | | | | | | | Wied ish (1) <numbey of resources A> number of proves. seu safely allgorthna Woik= aveulable =a 38 & 1 = 3 Finish €13 = False aise Panel te [ete Eete [Stepas fr v=o » Wed po = 7,4,3 Finish cop = Rise, Meelswork , 74 353 3 2 CRlse] 80 Po mut wad ate for vs) | nol P=1 aa Frush ts fal se Neo < work , 1228332 Chu} s 3:- Work = worke + allocation = 332+ 200 > S532 Sop, is th safe skabe. Finish cl = bu , get Slep 2, for tz 9, rool Pes 60° Finish a= Ralse ¢ | neool swotkh OOS 53 2 L false] So | fox va, wed B= ott Rinish Caj= false ¢ Need < work, o 11 $ $32 Chu) Pa must walk. So P3 ts ww safe stabe Wwoik = Wotk+ allocation S324 2 11 aoe a Finshea) = bua, goto skpe for v=4, rool P= 4 3] Fiuisht4) = false 4 Weed < wotk 4 31 < 443 hus) 50 Py In safe sbabe step 51- Wolk = work + allocation 5 IAS 4+.0 © 2, D>r4s Frush Caj=tue eoto skpzw fo Uz ved Po = 143 Fiuish Co = Rise Neel < work , 7435.74 5 Chua} | $0 > ws im safe stabe Work = Wotk+ allocation i Seto uation | =>195 | Fiiush Ca) = thus , goto step 2 \ | for ca, muted P= b 00 | Piwsh co = False | Wwool < Wk, b00 = 155 80 Pp, mwt be In safe state. Worle = Work + allocation “24654 3028 =lo 5 7 Finisher = brus, ste Cruishcia= tur Ry ozt rocess | Allocation Need Available ABC A BC ABC Po 010 qa ests aoe) Pa e002 |o2 eo Pr 302 600 Ps 2 ii o.1i1 Pa 002 431 Vere we mut obermineg whether ghiy new syskem stabe ts safe Tm do so we again execuke safety algou'thra on shuctue. mee Spt see) [ried Tat asa as rte Needy. gi pee | _ enkeWik vata, Finish [3] «fase and eed, < Wr eke 5 Work = [273 10, SOP, must be keptin safe sequence aaa ‘ So. i 238 6 a. + ish [lasfatefeeaeTase] Works Wisi atoitin, 7?) | [Enh [eveliueleineling] = 8 o™ = Fort S07] | | workefz[aTs for feese7.43 ¥es—zay wes aa Hewes, 0 key Fish 01s fase ana Weedy> Won sit [aleefotafcefana] | | | eh lisa and Ged, < Wot [Sore mustwait Gut Need= Wow inh [tose oF must be kent in safe soausnice = = For Fs] | [rorina ve ees=0,2,0 GEE RED Need, 4,31 iscaion, = 9 Fish as fae ana Weed, « Wow? | | [Rat ia and GED x sos mustbe kept in sre sence SoPamust bokeptin sae sequence asp fans aa0__nea aes Work = Work +Alocstion, wok WSEeaESE, 5) | [ene [neuen is +. tJ re Hence the system is in Safe state Finish = [false[true|fatse|fase|false] oi 38 8 fev] Finish = [tsi terol Tost Tort ThesafesequenceisP,Ps, Pe PePs fede 60,0 MBs aaa Fish (aistaseandeeds > Wort |) Fn ors tave snail «Ws Soy mustwat so Pamust be keptin safe sequence Pead lnele _Debection:- dn dhe absene oF dead Lock prevention or Avoielane mechanisms, dha system mut be able to detect Coole ans Yernver fom 1%. Thue exe two pessibivlia Ry Aeaullocle clebection. x In deal lock eletection algorithm vhat uses cho Variant of dhe resourte allocation graph called 4 wast for_qraph- 4 we oblain du graph from dhe Yesouru allocation graph by tempving dho yesoure nodes anal Collapsing dhe appropriate edges. * fn edge Poh ina walt fer graph means Pe t's waiting foi Py to yelease a vesourte Pi needs, Resoure allocatttoo geph wait By repk To dlebeck ch cleaol leks dhe system Moods > maintain dhe usait fer ph anol periockically invoke | | \ lon algoritho Saat searches for cycle in dhe gph: | @ several _inslones oF 2 resoure type The wart feu giaph scheme ss not applicable b a resource allocation system with muttiple Instances of each hesoure type. The algoritnrn employs several time Varying alata studores dhat are sintiley to dhese weal in bankers algorithm. » available. A veetor of length m indicates dhe umber of vailole siesounss of ath type. 4 allocations: ‘iam mabrix cleRnes dhe twmber oP ~esounes of ead dype eunently allocabeel to each prness. % Repub: nxm mabrix crabieabes cha cument request of each process. * detection algerithin:- 1. Let work 4 Fish be vectors of length m and n, Vutialize werk = available Ry (e011, UF allocation; +0, ¢hen Gitish c's = false, 1P allocation; =o dhon Fish tia = bus. 2) Rn an ‘uulex ¢ such dhab | both, a) Rrish tis == false » Roguost; = work ak wo suto Veni geto skp. 3. Worle = Worle + allocation Riuish ci3 = true goto step 2 ae aR Rush ci9 == alse. Ry som U, oglen, dhe system 5 In lead Lockecl state. Deal toele Reenvery :- wheo dha deechon agente determina dhat a elendldel. enusbs Several alteinahves ate available ena [possibility is to tnfoim she operator dhad dhe loool Loca has Ceuured anal Let dhe eperatoY cloal evitts dhe least Lodz manually. Mather possfbilty 1s to let dha sysbern yecover Ffom dhe dead loele automatically. Thee aie two option for breaking a lead love = process jbeumination ;- a Resouie Preenyption POSS bermation= a Abort all eleaol love processes :— a Poort on process at a tia. Until dhe deaat Loekect cycle vs eliminabeel. * In whuch elder should we choose to abort > priority of dhe process Yow Long process has Computed, ancl how muds Longer to | b completion. | Ly Resources cha process has used. | Resources Process tects to complete. | bs how many Processes evil! neecl to be bexninated, | & ds process Yntevathve oy bakth.2, IReboizte preemphoor & | IP preemption Ns Yeguited to deal wit dleadloces {dha Smee {ssus reed to be adkdiessed. | © Selecting a _vietin | wlth Yesourres and which proese: are b be Preemptecl.. 5 un Process termination we musk determin. the ender ef preemphion, | © Roll bacts :- | Retum to come sa shate, ‘estat protess Px chat stake @® _Stewation:- To avoid Starvation we musb ensure drat a Proess con be piekeel as a wicim only a Finite number ef time, Tha most common solution ts bo induole dhe pumber ef Yo bates én dhe cost factor. Consicler dhe system Consisting of Provesses ‘Lro,P.Pe ++ Pa-iJ- Each process hu a 8eq mont, oF code callecl as conteal section, én which dhe protess may be changing common Woriables, ae & buble, wstiting a Fite and soon. Tre Important feature of Sho system 18 dhat whon one process ts executing In Ih extteal secton, no otter protess Y's Glloweet to enetute in TEs eritical seetion. whith ‘new «to {wo prowesser ane executing cn dhe emiteal section at dhe same time. | do Z lentiy sector | exitteal Section | Yemainelei section Swhileew: dn dhs each provess nusb Yepuast permission 0 enter Yes enitical section. The sechoo of exde implementing dhs teguat Is dha enty section. The critical section ts Fottowea ty an ent section. the yematning cocle v's dha emandei section. The enhy seclion andl eb sechon are lenclosel cn boxes bo haghligt chase important segments oP code. eg'- : x Consider dha scenario, Where Money 1's withdrawo from dhe bane by both dhe cashier § atm machines. * consider de auount having che balan ef 10000). when a cashier withcaws dhe money 1} bake 2 second for dhe balane bo be updatecl in dhe acount. * dt is possible to wwithcaw ooe/- fiom cashier and within dhe balance to be Updated tn the @ucounkan Hime oP two setonels anol also evithehaw amount of booo|- From atm. * Thus ¢he total mony withdrawn becomes greates shan dhe balanw ef dha bank amount. Ths happena because 6P 4wWo ewitrchawals locuring at dhe same time. In dhe case of dha crittcal section only ene withdvawal should be possible and it can solve tui problem. The solution to dhe entieal section problem must sanshy ote Ritowing dinee equite mants. L_ mutual enclustog:- at process pe vs executing \n th critical section, Shen no ether process can be executing io choir exieal Settions. & Mrognessi: DP no provess 1s executing th ibs oneal section extol Some process wish to enter dhuiy embvea) sections dhon only dhose proteases Jhat are not executing cn lilt Yemaindet sections can partreipate. In dlecicling which evill enter its atitical section nor’, anol di selection cannol be Posipencal inclefinibely. 3 Bourle_waiting | There exis a bound oF wait Limi on dhe number | ef hme dhab otter processes aie allowed to enber | dhely embical section aber dha process has made a | Yeguait to enter its cnheal section anol bere | dhat yYeguat 1s granteck. Two — gunaval approach aie wee to hanclle enitical Sections in epexating systems, | © frcemphve wemele:: { Tt Allows she process to be preempted evhile it ts yung ch leornel mode. ® von _Preemprve leeynel s:- | gn non preemptive kemel eloes not allow a | process running tn leernel mode to be preempbeel, a kernal mode process voll tun until i enuish kernel mode, blocks ex voluntarily —yellds contol ef dhe cpu. i SS Synchiowation Henclwore:- problere. synchronization problem can be ‘Solveel ey software Gd well as hovdwere Solutions. gn jSyncnonizetion Vorctware we explore several move solution to ‘dhe esritical Section problem uving bednniguas Yangings from. herdware bo sofware basecl- Ail dha solution axe baal on dha premise of Loetaing :- * Definition of Banal sete iuhuctions:- D+ Ys dha morhua Cuhuchons eraterle are emecubed Qlonucinshuctons. meau al a tine only ene WS erecrbent. pale Testanalset( boolean atoiget) Process oy \nstruttion |? yy is hs, Yekevn hu boolean y= atayget | Atoyge’ = bua; Yeu yu; |* mataal enclusion sh Testenalsed(2:- | alo zt while testandseb(4 lous); oxtticl Section: Loew = false; Swhile Crue; X Swap functions: Note swap Uboolean aa, bodean ab) ow] Li boolean temp; | bemp = aa; aQ = ab; ab = bemp; 3 |a mutual entlusion ireplemmntation with swap ¢- | do j i | bey =trun; | | while key == hue) sw ks foe | Jap( glo, 4 key) A iad | enka Becton 22 2? ‘l . | Unc = false; z & i J unite Chua): : [Benaghetess Semaphore Ys dhe cyst! ation too} which can be usec for ever coming dhs emitieal section problem anol syndmonization problem. Semophores yeBis to dhe integos variables dhat ane primarily uredt bo Sowe de embeal section problem via pombining two of dhe atomic. proteclunes, wait and sygnal or Process syncinonization. a Th aemaphore ‘8 que @ Wwimal thbeged x The Semaphore canwt be a nagative. » The lead value Fy dhe semaphore 1 zaroto). & Tre maximum value Of semaphore can be anything. There are dwo Slandavel atomic epenations aye Weal semaphore are. QQ wasters Semaphore 'S v9 the tntegt variable dhal can he atcerseol by vaaibeo Ranchons. The waite) operations originally Ferment as P. | weut (9 | t i wlule (sso) | Aho operetivo s--; 3 | G2 signal - | The argnat eperation 1S Weal to upelote dhe value ef Semaphore. The Semazhore value v's upolateel whan che now Processes are teadly to enter dhe critical section. The igual operation a originally term cu vl | signal (3) | < St; A rhedhication tothe *ntegor value of Semaphore in Aha waibe> & signale epenations must be enduivisibly. That ts ten ene provess modifier dhe Semaphore valu, no othos provess pen simuttonaowly mrodify Shad Bame semaphore value. ® wautc> —> PLfiom Dutch worl proberen, which means “to test”. Signal) > V Cfforn Dutch word Nethogen, which means * yo increment", ype ef demaphores:- tounting semaphore ;- & Ys Value CoD Yange over an unrestricted clomafn ¥ Jt 1s Wed to eontol avo» to a yYesoures dhor has Multiple tubwoces. 2. Bineny gomaphore:. \ | x The volun of dhe Lomhery semaphore can range only between © and |. & on dome Syptems binany semophores Qe tanawn as mutex Loeks, hod Provike mutual exclusion, do Z wate mutex); exttteall, Becton: Signal Cmuterd; Yemetineles section Sule Semaphore implementation. To overcome dho nea fy busy wanting, we eaun moo fy dha dafinition of dhe wait ane 5\gna) emophore operations, wf with eath semaphore dhete ts an asouatel woltitg 7uslt- each enky tn dhe ewaibing queue hos duo elata terns. # value Cintegor) * Pointer to nent Yetorel tn dhe Lish | The eperations ove, @ block - plow dhe prowess envoluing dhe Operations | on dhe ayprepriake wating — gueus. © wakeup: Remove one proses cn dhe wartirg, quoun | and plow W di dhe veady queue. Lapbmension ¢ OP amit: wai Céemaphore as) ie Svalue-- > (PCs valua; 3 Smplumentation of oF signal = a as) 8> valur++; Re value <0) Tide dho pros P fim s—list; @ 4 DawenPO; Diszalvantoges oF _ senapheres- | © deo loots :- Two of more prowsses are twarling Inde Finikely ‘fos an event dhak con be eamed by only one of dhe {varhing prowsses | © Btowahon:- nalefiaite blocking . B provess over be yemoved [rom dhe semaphore queue in hich i} is teed suspended - Te example for adinck €ncl starvation tonuaph auordig to Senaphore. ts Po P, wwibCs); wart (0) weu't(a@); uautis)s | signal (5); sigralce); | Signal (8); signal (52 | eta blenu oP gynchroni2ahons:- eset Bu Per problem: | x The botuncled buffer problem 1 dhe one of dha Classical problenu 6? synch nization. ® HW othowwise calllel a proclut consumer — protlem. * The 1s a buffs of n slots ® Gach Slot Vs capable Of storing ona unit of data. * Thore are two Prone vunning @4 produ arcl tonsumar. | produ! | hore. | Tho produey tie to \nsert data Into an empty stot. | 4 The Consumer Iria to yemove claba fiom ited slot in buPPr. ¥ OF dia buPRer ts fan dhon procluwt cant abb to Tet naw data into baffr. * AP He buffer is emply ghon consumo cant able to Yemove any data Fiom loubhn. We Con Untowpre) dhe Feitowing toda a dhe [Frock proelucing fa loafers for dhe consumer of @ dhe Consumtar yroduuing empty bul for dhe produc. & The muten semaphore fproviclos nutual exclusion fy Ques to dhe bufpy poo! anol is initabred go dhe Value }. Buffs of slots. Ls consumed | % The emply and fall semaphores are weal bo | town} emply—and number of empty anal Rat bufGas. | * The Semaphore emply U initialized to dhe valua n. ® The Semaphore Fat is initialized fo dhe value o. rude, of _Prroctutor, protens:- elo . Wark Cemplyd+ > wait until empty >o and eleviernent empty, Wweut Cmubex2+ > acquire Lock , 7* add data to buffer »/ Signal Crubexed, > yelease Loew Sinai fall d; > cnerenent Rul | Suwhilectave> | | ara a wait CRiuy; > wait uantt finso 4 dovement Paw won't Cruaten>,- Zs yemove lato From tu PR a/ Signal (mater Signal Lempty); Swhile Crave © Readers writers problem: * A alatubase Is to be shonedt among several conuent Prowsses, Some of die Prowes want only bo seca) cata ee dha database Other [rows wank only fo updabe Cjeadt and unite here only ~feaching mean ‘hs ‘Yepresented ay Reader, “he updlation Ube ead ¢ vnvibe are, calleal as _caribess IP two readers are auess shorrest late Almulta neously YO yroblomy can ouuredl in dhe result. APF writer andl cites Ube -adl(either Yead a veadey 1 A wwriber) moan i will become soma i'sue on Yesulb, To ensue chat shoe elicitin clo nok anise ve Tequire chat dhe uoviters have encetunve auen bo dhe shored datubue. This tinal of syndnon ation Problems are called (63 Readers - uositors problem. Jn dhe teolem uniters Shase dhe following dota shure. Semaphore ~u-muber = 1: Semaphore mutex =1; int - Xeod_counk = 07 The semaphore Mutex and iw-mukex ave Nwaline to 1, tead count is nabired tp 0, Tha semaphore w-mutex 1S eommon to both yeader anol euriker prota sseas. Problem, dhe, readot processes lsruvksne of _voriled _yrown:. t walk (yw. mubexd/ | hs coriting, y's potformned x) Signal Cyuy.mnuden): Suhile Ctrve); he _Shuviere_ OP readers poeess.- do g walt Lmubexd + Yeoul_ Count ++; a ne of aeaslen to be tneeased VP Cyeawl. count = = 1D Wwautlvw. muted: Signal (mutex) » 7x Yeading, is yerfrmecl a/ wautimutex); ‘Yeawl_ count -~/ —> yeadlor unnb fo leave iP Ged. count ==0> Signa) (xu tuber) ; 8 Wgnal maber 3 SuwhileCtaved; The = mukex Semaphore Ys wed bo ensure Mul bull —encelunon when dhe variable yeoul_ count 1s updated . Neal. count vamiable (seeps Vow many prowe axe Cumently Yeooling dhe object. Dini hilosophers blem:- # The lining philosopher problem is dhe clessrcol problems of Syncnonization which says dhat Five Phulosophers ave sitting Ayound a etvulay table anol dheir fob 1s to dhink and eat altemaively - an bowl ef wie ts plaeel at dhe contre oP dhe table along wait Five chopstieles for each of dha philose phors, T ext a phulosophor reols both dhwir yight and lef chopstiebss. A philosopher can eab only iP boty teA and right chopstiels are avaulable. Wwe eperatiom are perfermet by a philosopher i's Trinlaing andl eating. when a philosopher dhinks, he ov she cloes not Interact voit dheit colleaguas. ffom time to time dhe Prulosopher get hungry and hie to Pickup dha d¢wo chopshees hab aie closest to hor, Plulosophor may pickup only one chopshicy at a ime, she unl nob pienup the chopstick dhol Is already ch Sho ord of a naighbour, when Yungig philosopher has bolts chopshiclu at dhe dome time, she en eoithout releasing dhe chopsteks. when she Rinsho) eating dhey pu cleron both Chaystiee anal stom Shan bing, One Simple solution 18 to yepresent each chopstick curt Sha Semaphore. 0 philosopher hia to giab a chepshee by executing a walbld operation on dhal semaphore. sho Yeleases her chopsticks by executing dhe oygnale> Speration en dha appropriate Semaphore. | do z Wwou't Cchepshiek e135 Walk chopstick i419 %59/ signal Cchopstiek C19) Signal Cchopshik Uis4ox%s>; & pllows atmost 4 philosophers to be sitting Simultaneously at dhe table. | * Blow a philosopher to picrup — hor chopsticks only IP boty chopsticks are available Use an asymmetic solutions, an odlel number Philesophos | Picks Up Frist her tek chopstick anal then her Yight chophrets Whore as an even numbereol philosopher preks up hor sight chopstick anol dhen dhor le Re salir —— ( \ @ Moutors:- vapisa synemo nization techmgus hort eneables Sry of to mulual exclusion and, dha walker fy a given | condition become tus. | ¥ ab Is an abshaet data iype. & ob he a shume variables anal a collection of ae executing on dhe shared variables. ae prown ray nob aliveetty auoyel dhe shored variables. Yrowoluies repuirect to allow several prowsses to auess de Shorea data variables. only om rows may be autive do a monitoy. ® Tho othat prowse nasal bo auon dhe shaveal variables | Mat be tn guaua- * ome dhe prow G bo be Finished cheiv exceuution,, may ve yeleaed dhe shored variable fox dhose Ho prowanes are wouting to dho gueu fer dh shad variables. yotous | Nonitoy — Monitor noune $ : I shoned veriavles daclorations is tion Pn D | font ite) | : Ba Initialization code ¢> ; tron pat) L oo : The monilov Construct enserres dha enly one pros, ia & He ts achve colthin dha monitor. The Progra mot doesnot ‘neck to ude dh gynchontration constants enplicitly. fox dhe pouoonfa heelelig oP gynehnonination schema dha Adebitonal Synemoniretions' mechanisms ate ued » Thue are ‘nathennisms Provided by dhe Concl’hon tonyhruct - noniter “Ine only eperations dhat cun be unvoked en a eondition vatiable axe, cab? § signal x-weibC> —> dhe process envoleing dha eperation Ys Suspended until anottar process Unvotees. %-signald —> Ww eperation yesuma exachy one Suspended process. oR po rows & to be swpencled ,dhan che Signal operation \w no effect. dhot 1's dhe stabe of xs | | | dtx Sama aa iP che eperation had twver been enecuted.

You might also like