Aa e{  P `@P   `0@P@(HH $ @d HHHH̀̀̀ff@  d Footnote TableFootnote**.\t.\t/ - :;,.!?72 cN* dTOCHeading1Heading2   PEquationVariablesJ ;`<<=7=P=i=;B;D;F;H?!A&UBaBu  <$lastpagenum><$monthname> <$daynum>, <$year>"<$monthnum>/<$daynum>/<$shortyear>J<$hour>:<$minute00> <$ampm> on <$dayname>, <$monthname> <$daynum>, <$year>"<$monthnum>/<$daynum>/<$shortyear><$monthname> <$daynum>, <$year>"<$monthnum>/<$daynum>/<$shortyear> <$fullfilename> <$filename> <$paratext[Title]> <$paratext[Heading1]> <$curpagenum> <$marker1> <$marker2> (Continued)+ (Sheet <$tblsheetnum> of <$tblsheetcount>)Heading & Page <$paratext> on page<$pagenum>Pagepage<$pagenum>See Heading & Page%See <$paratext> on page<$pagenum>. Table All7Table<$paranumonly>, <$paratext>, on page<$pagenum>Table Number & Page'Table<$paranumonly> on page<$pagenum>Heading <$paratext>EHTML Headings++A335579A<<>>@@AP;b;d;f;h;j;l;n;p;r;t;v;x;z;|;~;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;<<<<<< < <<<<<<<<<<< <"<$<&<(<*<,<.<0<2<4<6<8<:<<<>:a.I?;b.ID;c.IE;d.IF;f.IG;g.IH;e.II;h.IJ94.IK:a.IL;b.IM;c.IO95.IP:a.IQ;b.Ix97.I_96.I`:a.Ia;b.Iy:a.Iz;b.I~98.I:a.I;b.I;c.I;d.I9 9.I:a.I;b.I;d.I;c.I;e.I;f.?WI;g.I;h.?EIEI?IEI?E@~F@E@II@ II@ @ @ @ @ @ @ @ @ @@E@@@ @ @ @ @ @@I@@@J@@J@W@E@@E@ @ @ @ ?PW@ @ @ @ @ @ @ @ @ @ @ @ @ @E@@@@@W@E@@E@ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @ @E@@@W@E@@ @ @ @ @ @E@ @ @ @ @ @ @ @ @ @ A A A A A A A A A A  A EA A A AAWAEAAEAAAAEAAA A!A"A#EA$A%A)UA*VA+SA7WA8EA9A:EA;A<A=A>A?A@AAABACADAEAFBBBAJAKALAMANAOAPAQARASATAUEAVAWAXAYAZA[A\A]A^AjWAkEAlBEB B B B B B B B B B B B B C C C C C C C C C C  C  C  C  C  C C C C CEAAAAAAAAGWGWGGEGGEGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGEGGGGGGGGGGWGEGGGGGGGGGGGGGGGGGGGGGGGGEHHHHHHHHHH H WHDEH H HHHHHHHHHHHHMHEHHHHTHUEHVH)EH-HEEHFHWHXHYHZH[H\H]H^H_H`HaHbHcHdHeHfHgEHhHiHjHkHlHmB]#B^EB_B`EBcBeBgBiBkBmBoBqBsBtBwByB{B}BBBBBBBB#BEBBEB B B B B B B B B B B B B B B B B B B B B BEBBBBBLH}#BEH~EHHEHHHHHHHHHHHHHHHHHHHHHHHHHHEHHHHHHHHHHHLC:WCCECDCMECNCOIC3C.C.C.CCD.D@C.C.C.C.C.C.C.C.D}D.D.D.D.D.D.D.D.D.DD.D.D.D.D.D.D.D.D.D̀G WE3F[F\OF]OEOF3FFрFFIGWGUEGGGGGGGGGGGGGGGG G!G"G#G$G%G&G'G[EG)G*G+G,G-G.G/GdG1GfEGFEGGGgEGhGiGjGkGlGmGnGoGpGqGrGsGtGuGvGwGxEGyGzG{G|G}G~GGH#HEHHEH H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H H HEHHHHHHHH#HEHHEHHHH H H H H H HH H H H H H H HH H H H H H HEHHHHHHLH#HEHHEH H H H I I I I I I I I I I  I  I EI I IIIIIIIIIIIEIIIIIIIII; i.I; j.IWIEIIEII I I I I I I I I I I I I I I I I I I I I I I I I I II JJ JEJJJJJJLJ 9dq5+d? d;]d;L HmR;MHmRHRHRFootnote Hr@;NHr@HzHz Single LineH;O Footnote ;P  HD;Q HDHH Double LineH;R Double Line;S ;T H;U  Single Line;V HZ;W  TableFootnoted5p77 EGxR;XEGxREPwEPw TableFootnoted;^dEl d;_d1QRUX[^adgjmpsvy| %).1W/Bm }d ;ad WaHTML Mapping Table }Hd ;cHd Wa }Hd ;eHd Wa }Hd ;gHd Wa }Hd ;iHd Wa }H;kH! FrameMaker PA Source Item }H ;mH Wa HTML Item }H ;oH Wa }H;qH W aInclude Auto# } H;s H W a Comments }H;uH W a }HH;w HH W aElement }H;y#H W a New Topic? }H;{H Wa } H;} H Wa }H ; $H Wa P:Date Line }HH ;#%HH WaP }H ;$&H WaN }H ;%'H WaN } H ;&( H Wa }EH ;')EH Wa P:Reading }HEH ;(*HEH WaP }EH ;)+EH WaN }EH ;*,EH WaN } EH ;+- EH Wa }QH ;,.QH WaP:Title }HQH ;-/HQH WaH* }QH ;.0QH WaN }QH ;/1QH WaN } QH ;02 QH Wa }]H ;13]H WaP:Body }H]H ;24H]H W aP }]H ;35]H W!aN }]H ;46]H W"aN } ]H ;57 ]H W#a }iH(;68iH( W$a P:Numbered1 }HiH(;79HiH((%aLI &a Parent = OL Q'a Depth = 0 }iH(;8:iH( W(aN }iH(;9;iH( W)aY } iH(;:< iH( W*a }H ;;=H  W+a P:Heading1 }HH ;<>HH  W,aH* }H ;=?H  W-aN }H ;>@H  W.aN } H ;?A H  W/a }H(;@BH(  W0a P:Numbered }HH(;ACHH(( 1aP 2a Parent = OL Q3a Depth = 0 }H(;BDH(  W4aN }H(;CEH(  W5aY } H(;DF H(  W6a }H ;EGH  W7a P:CellBody }HH ;FHHH  W8aP }H ;GIH  W9aN }H ;HJH  W:aN } H ;IK H  W;a }H ;JLH  W<aP:CellHeading }HH ;KMHH  W=aP }H ;LNH  W>aN }H ;MOH  W?aN } H ;NP H  W@a }H ;OQH  WAa P:Footnote }HH ;PRHH  WBaP }H ;QSH  WCaN }H ;RTH  WDaN } H ;SU H  WEa }H(;TVH( WFa P:Bulleted }HH(;UWHH((GaLI Ha Parent = UL QIa Depth = 0 }H(;VXH( WJaN }H(;WYH( WKaN } H(;XZ H( WLa }H ;Y[H WMa P:Heading2 }HH ;Z\HH WNaH* }H ;[]H WOaN }H ;\^H WPaN } H ;]_ H WQa }H;^`HR! P:HeadingRuPAnIn }HH;_aHH WSaP }H<`bH WTaN }H<acH WUaN } H<bd H WVa }7H <ce7H WWa P:Indented }H7H < dfH7H WXaP }7H < eg7H WYaN }7H < fh7H WZaN } 7H <gi 7H W[a }CH<hjCH\! P:TableFootPAnote }HCH<ikHCH W]aP }CH<jlCH W^aN }CH<kmCH W_aN } CH<ln CH W`a }]H(<mo]H( Waa P:TableTitle }H]H(<npH]H((baLI ca Parent = OL Qda Depth = 0 }]H( H "W4a }©H <=?©H #W5a }H©H <>@H©H #W6a }©H <?A©H #W7a }©H <@B©H #W8a } ©H <AC ©H #W9a }»d <BF»d $W:aHTML Options Table }D»d <D»d $W;a }D»d <D»d $W<a }D <CGD %W=a }DH <FHDH %W>a }H <GIH %W?a }D <HJD &W@a Image Format }DH <IKDH &WAaIMAGGIF }H <JLH &WBa }D <KMD 'WCaBanners }DH <LNDH 'WDaN }H <MOH 'WEa }D<NPD(F! Banner ReferPA ence Frame }DH<OQDH (WGa }H<PH (WHa }D(<DSD((F)I! Copy Files  Imported by PA Rerefernce }DH(<DRTDH( F)WJa }H(<DSUH( F)WKa }DD <DTVDD F*WLa }DDH <DUWDDH F*WMa }DH <DVXDH F*WNa }Vd <DW[Vd F+WOaSystem Macros }?Vd <D?Vd F+WPa }?Vd <D?Vd F+WQa }f? <DX\f? F,WRa Macro Name }?fH <D[]?fH F,WSa Replace With }fH <D\^fH F,WTa Comments }r? =D]_r? F-WUa StartOfDoc }?rH =D^`?rH F-WVa }rH =D_arH F-WWa }~? =D`b~? F.WXa EndOfDoc }?~H = Dac?~H F.WYa }~H = Dbd~H F.WZa }?= Dce?F/[! StartOfSubPADoc }?H=Ddf?H F/W\a }H=DegH F/W]a }?=Dfh?F0^! EndOfSubPADoc }?H=Dgi?H F0W_a }H=DhjH F0W`a }?=Dik?F1a! StartOfFirstPASubDoc }?H=Djl?H F1Wba }H=DkmH F1Wca }?=Dln?F2d! EndOfFirstPASubDoc }?H=!Dmo?H F2Wea }H=#DnpH F2Wfa }?=%Doq?F3g! StartOfLastPASubDoc }?H='Dpr?H F3Wha }H=)DqsH F3Wia } ?=+Drt ?F4j! EndOfLastPASubDoc }? H=-Dsu? H F4Wka } H=/Dtv H F4Wla }&? =1Duw&? F5Wma }?&H =3Dvx?&H F5Wna }&H =5Dwy&H F5Woa }8d =8Dx|8d F6WpaCross-Reference Macros }?8d =:D?8d F6Wqa }?8d =<D?8d F6Wra }H? =>Dy}H? F7Wsa Macro Name }?HH =@D|~?HH F7Wta Replace With }HH =BD}HH F7Wua Comments }T?=DD~T? F8Wva See Also }?TH=FD?THF8w! See Also: PA <$paratext> }TH=HDTH F8Wxa }n? =JDn? F9Wya }?nH =LD?nH F9Wza }nH =NDnH F9W{a }d =QD d F:WaGeneral Macros }?d =SD?d F:Wa }?d =UD?d F:Wa }?d =WD?d F:Wa }? =YD"? F;Wa Macro Name d= d= d l d= do  WBm }d = d  <W|aHeadings Table }Hd = Hd  <W}a }Hd = Hd  <W~a }H= H =!Paragraph ForPAmat }HH= HH  =WaHeading Level }H= H  =Wa Comments }H= H >W aTitle }HH= HH  >Wa }H= H  >Wa }KH = KH  ?Wa Heading1 }HKH = HKH  ?Wa }KH = KH  ?Wa }WH = WH  @Wa Heading2 }HWH = HWH  @W a }WH = WH  @W a }cH = cH  AW a }HcH = HcH  AW a }cH = cH  AW a HHˆ?HHˆ†H!! V `Improper Nesting Example Y,` Introduction \ wOne of the limits on the use of parbegin/parend, and any related constructs, is that the program involved must be propI@lerly nested. Not all programs are. For example, consider the program represented by the following graphs. _b`The Program as Graphs ` w"h  aH`%Using  fork/join  Primitives b[`GThe program equivalent to these precedence and process flow graphs is: eZ` t6 := 2; h5:` t8 := 3; i`'S1; fork p2; fork p5; fork p7; quit; j`!p2:S2; fork p3: fork p4; quit; k`p5:S5; join t6, p6; quit; l`p7:S7; join t8, p8; quit; m`p3:S3; join t8, p8; quit; n`p4:S4; join t6, p6; quit; o`p6:S6; join t8, p8; quit; p`p8:S8; quit q`4where S i  is the program for p i . rAH`+Using  parbegin/parend  Primitives sRO wTo see if this is possible, we must determine if the above program is properly nested. If not, we clearly cannot repre^N@rsent it using  parbegin  and  parend , which require a block structure, and hence proper nesting. qtnN ]Let  S ( a , b ) represent the serial execution of processes  a  and  b , and  P ( a , b ) the parallel execution of processes  a  and  b .  Then a process flow graph is properly nested if it can be described by  P ,  S , and functional composition. For example, @ the program HHˆ?HHˆ7H l|33k ?8E }?H =[D #?H F;Wa Replace With }H =]D"$H F;W aHead }H =_D#%H F;W!a Comments }? =aD$&? FCW"a }?H =cD%'?H FCW#a }H =eD&(H FCW$a }H =gD')H FCW%a }d =jD(.d FDW&aCharacter Macros HHˆ;"HHˆ+Ge HHˆ;$3HHˆ**l}?d =lD?d FDW'a }?d =nD?d FDW(a }? =pD)/? FEW)a Macro Name }?H =rD.0?H FEW*a Replace With }H =tD/1H FEW+a Comments }? =vD0B? FFW,a HUV ;.HUV 3Ge HUV ;05+HUV 22l H$ ;1H$ 5Ge H$ ;33H$ 44l HHˆ;4HHˆO^//7 `(Process Synchronization and Cooperation 2` Parallelism 3u`concurrent vs. sequential Bt`!logical vs. physical concurrency `%process creation: static vs. dynamic >`Proper nesting `S ,  P 0s`definition of proper nesting 1`precedence graph 4`Precedence relation < 5`predecessor process 6*`proces domain, range 7` equivalent systems of processes 8` determinate system of processes ;`Bernstein conditions 9` mutually non-interfering system :`9Theorem: mutually noninterfering systems are determinate <`maximally parallel system =wa`&Basic concurrency language constructs >`cobegin/coend ?+`fork/join/quit A`Critical section problems B`producer consumer C5]`Mreaders writers; first gives readers priority, second gives writers priority @`dining philosophers EM`Software solutionss F`Dekkers, Petersons GeT`bakery algorithm DrD`Hardware solutionss H`disable interrupts I` test and set Jݴ`Basic language constructs K` semaphores L*~`sequencers and eventcounters M`>simultamepus primitives  SP ,  SV ,  P-or N` send reveive OwG`!Higher-level language constructs P`abstract data types Q`ccomparison of constructs: constraints, expressive power, ease of use, portability, process failure S` monitors R`crowd monitors T`invariant expressions U`path expressions W`predicate path expressions X`CSP $`RPC A%`ADA HHˆ;6HHˆ 66 lS?!99SS?!8:8:SBS?!9G9GBSd;;<@H$ ;<;>H$ == l H$ ;=;H$ <Wh8January 13, 2000ECS 251 Winter 2000Page 1  HUV ;>;<@HUV ?? l HUV ;?;HUV >WlCLast modified at  10:01 am on Thursday, January 13, 2000  HHˆ;@;>HHˆAA l HHˆ;A;HHˆ@W` }?H =xD1C?H FFW-a }H =zDBH FFW.a d=~EEd=DdFF l d=DdRCERUX[^adgjmpsvy| %).1BS?!:H:HBSS@!GIGISS@!HJHJSB@!IKIKBB@!JLJLB@!KMKM@!LNLNB@!MOMOBB@!NPNPBB@!OQOQBB@ !PRPRBB@ !QSQSBB@ !RTRTBJ+P@ !SUSU IJ+P0/'@ !TVTV/'B/NGI "l@ !UWUWBIGI "l0K/@!VXVXK/K/KKJzb@ !WYWYIJzb0T// @!XZXZT// T/O "l@ !Y[Y[ "l0 e@!Z\Z\ e e L+P@ ![][]9L+P0e'@!\^\^e'e<C1@ !]_]_BC1102S@!^`^`2SGG "l@ !_a_aBG "l0K@!`b`bKKKG "l@ !acacBG "l0K@!bdbdKKKenl @ !cece[enl 0Kl<@!dfdfKl<lKTe 6@!egegTe 6Te]SCx䠉R@ !fhfhKSCx䠉R0V@ !gigiV]V TF@!!hjhjTFprecedence graph UE@"!ikikUEU*U* S1 TE@#!jljlTE``S2 UTE@$!kmkmUTEU`U`S5 TE@%!lnlnTE``S7 E@&!momoES3 1E@'!npnp1E11S4 1E@(!oqoq1E11S6 UE@)!prprUEUUS8@*!qsqs@+!rtrtR "l@, !susuRR "l0#/%@-!tvtv#/%#/#TW:@. !uwuwW:0\'@/!vxvx\'#\ "l@0 !wywy "l0#\%@1!xzxz#\%#\##\$-@2!y{y{#\$-#\G:~|@3 !z|z|:~|50 A@4!{}{} A "l@5 !|~|~ "l0#@@6!}}#@## ʉ"l@7 !~~ ʉ"l0@8!$~|@9 !$~|0' A@:!' AG' "l@; ! "l0#@<!###@=!@>! E@?! E * *S !@@!  !!!E $99@A!  $99$E$Ep1 f9@B!  f9rrp2 H9@C!  H9HHp7 $o9@D!  $o9${${p5 9@E!   9 p4 9@F!  9p3 $9@G!$9$$p6 $9@H!$9$$p8 mÀ@I!EmÀprocess flow graphT92-@J!ET92-8w@K !EwS@L !ESBS@M !EBSS@N !ESB@O !EB@P !EB@Q !EBB@R !EBB@S !EB TE@T!ETE  precedence graph Vӏ@U!EVӏV'V' S1 Tӌ@V!ETӌ]]S2 VTӌ@W! E VTӌV]V]S5 Tӌ@X!!E!Tӌ]]S7 ӌ@Y! "E "ӌS3 2ӌ@Z!!#E!#2ӌ22S4 2ӌ@[!"$E"$2ӌ22S6 Vӌ@\!#%E#%VӌVVS8@] !$&E$&@^ !%'E%' !ӆ@_!&(E&(!ӆ!'!'S ӇT@`!')E') ӇT E % @a!(*E(*% %B%Bp1 f @b!)+E)+f oop2 I @c!*,E*,I IIp7 %o @d!+-E+-%o %x%xp5 @e!,.E,. p4  @f!-/E-/ p3 % @g!.0E.0% %%p6 % @h!/1E/1% %%p8 [J@i!02E02[J process flow graphl @j!13E13l Qc33@k !24E24Qc33cQQ-ͪ@l !35E35Q-ͪQ-WIͯ"@m !46E46Iͯ"IͯIQͩ4)@n !57E57ͩ4)CͩRb4(@o !68E68b4(bDe$@p !79E79e$e8`@q !8:E8:8`CI(@r !9;E9;I(III&@s !:E<>"ͯ."ͯ"][",@v !=?E=?[",![&@w !>@E>@&%!K@x !?AE?A!K !*@y !@BE@B!*!""I@z !ACEAC"I"""[2@{ !BDEBD"[2"["X~w@| !CEECX_aw"NOJ1H3srFXw@}!DwDd@HH HHˆ@FHHˆ Hu` parbegin v`p1:a := b + 1; w`p2:c := d + 1; x`parend y`p3:e := a + c; z`would be written as {`S ( P (p1,p2),p3) |`We now prove: }`0Claim . The example is not properly nested. ~`:Proof : For something to be properly nested, it must be of the form  S (p i ,p j ) or  P (p i ,p j ) at the most interior level. `Clearly the example's most interior level is not  P (p i ,p j ) as there are no constructs of that form in the graph. a In the graph, all serially connected processes pi and pj have at least 1 more process p k  starting or finishing at the node Tn ij  between p i  and p j ; but if  S (p i ,p j ) is in the innermost level, there can be no such p k  (else a more interior  P  or  S  is @Yneeded, contradiction). Hence, it's not  S (p i ,p j )) either. HHˆ@FHHˆ KGG ld@KK HHˆ@IHHˆ--K3 `Maximally Parallel Systems 4,` Introduction 5 }A  maximally parallel system  is a determinate system for which the removal of any pair from the precedence relation I@=< makes the two processes in the pair interfering processes. 6b`Example 7*t`The system  S  = (, <) is composed of the set of processes = {  p 1 , .,  p 9  } and the precedence relation 8`]< = { ( p 1 , p 2 ), ( p 1 , p 3 ), ( p 1 , p 4 ), ( p 2 , p 5 ), ( p 3 , p 5 ), ( p 4 , p 6 ), ( p 4 , p 7 ), ( p 4 , p 8 ), ( p 5 , p 8 ), ( p 6 , p 8 ), ( p 7 , p 9 ), ( p 8 , p 9 ) }. =UU`5The processes have the following domains and ranges: :zf*`rIn the following, a bullet is placed whenever the process in the row precedes the process in the column under <. ?z 0  and `{ 10  ( number [ j ],  j ) < ( number [ i ], i )  do `11 (* nothing *); `12  end ; `"13 (* critical section *) `/14  number [ i ] := 0; `# 15(* remainder section *) `! 16 until  false; Y` Comments *k "lines 1-2:Here,  choosing [ i ]  is true if  P i  is choosing a number. The number that  P i  will use to enter the y@critical section is in  number [ i ] ; it is 0 if  P i  is not trying to enter its critical section. UUU: qlines 4-6:These three lines first indicate that the process is choosing a number (line 4), then try to assign a *U9~unique number to the process  P i  (line 5); however, that does not always happen. Afterwards,  P i  UU*@indicates it is done (line 6). ** lines 7-12:Now we select which process goes into the critical section.  P i  waits until it has the lowest number UUgof all the processes waiting to enter the critical section. If two processes have the same number, the one with the smaller name the value of the subscript goes in; the notation ( a , b ) < ( c , d ) means `&true if  a  <  c  or if both  a  =  c  and  b  <  d  (lines 9-10). Note that if a process is not trying to enter the *xcritical section, its number is 0. Also, if a process is choosing a number when  P i  tries to look at it, +@AP i  waits until it has done so before looking (line 8). S}` line 14:Now  P i  is no longer interested in entering its critical section, so it sets  number [ i ]  to 0. HHˆ@OHHˆNTPP ldATT HHˆARHHˆ(''T `Bogus Bakery Algorithm ,` Introduction  }Why does Lamport's Bakery algorithm used a variable called  choosing  (see the algorithm, lines 1, 4, 6, and 8)? It Iwis very instructive to see what happens if you leave it out. This gives an example of mutual exclusion being violated 0Wif you don't put  choosing  in. But first, the algorithm (with the lines involving  choosing  commented out) so you @#can see what the modification was: z` Algorithm  `|1 var (* choosing :  shared array  [0.. n -1]  of   boolean ;*) !`o2  number :  shared   array  [0.. n -1]  of   integer ; "UN`   #`3  repeat $`?4 (* choosing [ i ] := true;*) %`u5  number [ i ] := max( number [0], number [1],, number -1]) + 1; &`@6 (* choosing [ i ] := false;*) '`\ 7   for   j  := 0  to   n -1  do begin (`U8 (* while   choosing [ j ]  do  ;*) )`G9  while   number [ j ] <> 0  and *`{ 10  ( number [ j ],  j ) < ( number [ i ], i )  do +`11 (* nothing *); ,`12  end ; -`"13 (* critical section *) .`/14  number [ i ] := 0; /`# 15(* remainder section *) 0`! 16 until  false; 1e`'Proof of Violation of Mutual Exclusion 2dw Suppose we have two processes just beginning; call them p 0  and p 1 . Both reach line 5 at the same time. Now, we'll assume both read  number [0]  and  number [1]  before either addition takes place. Let p 1  complete the line, 0CLassigning 1 to  number [1] , but p 0  block before the assignment. Then p 1  gets through the  while  loop at lines 9-11 and enters the critical section. While in the critical section, it blocks; p 0  unblocks, and assigns 1 to  number [0]  at UUline 5. It proceeds to the while loop at lines 9-11. When it goes through that loop for  j  = 1, the condition on line 9 is dtrue. Further, the condition on line 10 is false, so p 0  enters the critical section. Now p 0  and p 1  are both in the critical UU?@§ion, viuolating mutual exclusion. 3? The reason for  choosing  is to prevent the  while  loop in lines 9-11 from being  entered  when process  j  is setting  'its  number [ j ] . Note that if the loop is entered and  then  process  j  reaches line 5, one of two situations arises. Either "number [ j ]  has the value 0 when the first test is executed, in which case process  i  moves on to the next process, or +number [ j ]  has a non-zero value, in which case at some point  number [ j ]  will be greater than  number [ i ]  b(since process  i  finished executing statement 5 before process  j  began). Either way, process  i  will enter the critical section before process  j , and when process  j  reaches the  while  loop, it will loop at least until process  i  leaves the @critical section. HHˆARHHˆQYSS lVA']VV^ A(U =QuickDraw PICT #%v  T XT7S/XT@/\XT.vJXTm.JXTddX"m"[.##########"!*"2;##########"!r"2`##########"d"S##########"i"{W########## =EndInset dA.YY HHˆA/WHHˆjp,,Y4 `Test and Set Solution 5,` Introduction 6 This algorithm solves the critical section problem for  n  processes using a Test and Set instruction (called TaS here). I@9This instruction does the following function atomically: 7W`B function  TaS( var  Lock: boolean): boolean; 8` begin 9`TaS := Lock; :`Lock := true; ;` end ; <` Algorithm =``1 var waiting :  shared array  [0.. n -1]  of  boolean; >`92  Lock :  shared   boolean; ?UI`. 3  j : 0.. n -1; @`"4  key : boolean; A` B*`85  repeat (* process P i  *) CUU`26  waiting [ i ] := true; D`!7  key  := true; E`]8  while   waiting [ i ]  and   key   do F`;9  key  :=  TaS ( Lock ); G`410  waiting [ i ] := false; H`,11 (* critical section goes here *) I`E12  j  :=  i  + 1  mod   n ; J`{13  while  ( j  <>  i )  and   not   waiting [ j ]  do K`F14  j  :=  j  + 1  mod   n ; L`<15  if   j  =  i   then M`$16  Lock  := false N`17  else O`518  waiting [ j ] := false; P`19 until  false; Q8` Comments R`Zlines 1-2:These are global to all processes, and are all initialized to  false . S*`Tlines 3-4:These are local to each process  P i  and are uninitialized. TU3 lines 5-10:This is the entry section. Basically,  waiting [ i ]  is  true  as long as  P i  is trying to get into its *critical section; if any other process is in that section, then  Lock  will also be true, and  P i  will loop ƶUuin lines 8-9. Once  P i  can go on, it is no longer waiting for permission to enter, and sets  wait UU ing [ i ]  to  false  (line 10); it then proceeds into the critical section. Note that  Lock  is set to (@Strue  by the  TaS  instruction in line 9 that returns  false . U*%' lines 12-18:This is the exit section. When  P i  leaves the critical section, it must choose which other waiting proUU3ygcess may enter next. It starts with the process with the next higher index (line 12). It checks each ?xiprocess to see if that process is waiting for access (lines 13-14); if no-one is, it simply releases the *z/lock (by setting  Lock  to  false ; lines 15-16). However, if some other process  P j  is waiting for Y"entry,  P i  simply shanges  waiting [ j ]  to  false  to allow  P j  to enter the critical section (lines 17-XUUQ@18). HHˆA1WHHˆT\XX ldA2\\ HHˆA3ZHHˆ}..\ V `#Classical Synchronization Problems W,` Introduction X uThis handout states three classical synchronization problems that are often used to compare language constructs that I@pher is a plate and to the left of each plate is a fork (so there are five forks, one to the right and one to the left of each 0U|philosopher's plate; see the figure). When a philosopher wishes to eat, he picks up the forks to the right and to the left vof his plate. When done, he puts both forks back on the table. The problem is to ensure that no philosopher will be @=allowed to starve because he cannot ever pick up both forks. ae vThere are two issues here: first, deadlock (where each philosopher picks up one fork so none can get the second) must xnever occur; and second, no set of philosophers should be able to act to prevent another philosopher from ever eating. HHˆA5ZHHˆY_[[ ldAa__ HHˆAb]HHˆŒUU_ e@A solution must prevent both. f Ž"h gm8`(Figure. The Dining Philosopher's Table Qhm7` HHˆAd]HHˆ\b^^ ldAebb HHˆAf`HHˆ‚//b i `Producer/Consumer Problem j,` Introduction k`[This algorithm uses semaphores to solve the producer/consumer (or bounded buffer) problem. lV` Algorithm mh`d1 var  buffer :  array  [0.. n -1]  of   item ; nt`L2 full ,  empty ,  mutex :  semaphore ; o`73 nextp ,  nextc :  item ; p`4 begin q`5 full  := 0; r`$6 empty  :=  n ; s`7 mutex  := 1; t`8 parbegin u`09 repeat (* producer process *) v`010(* produce an item in  nextp  *) w`(11 down ( empty ); x`(12 down ( mutex ); y`/13(* deposit  nextp  in buffer *) z`&14 up ( mutex ); {`%15 up ( full ); |`'16 until   false ; }`117 repeat (* consumer process *) ~`'18 down ( full ); `(19 down ( mutex ); `020(* extract an item in  nextc  *) `&21 up ( mutex ); `&22 up ( empty ); `123(* consume the item in  nextc  *) `'24 until   false ; `25 parend ; `26 end . ` Comments  lines 1-3Here,  buffer  is the shared buffer, and contains  n  spaces;  full  is a semaphore the value of which ˪mis the number of filled slots in the buffer,  empty  is a semaphore the value of which is the number 0U kof emoty slots in the buffer, and  mutex  is a semaphore used to enforce mutual exclusion (so only uone process can access the buffer at a time).  nextp  and  nextc  are the items produced by the pro@2ducer and consumed by the consumer, respectively.   |line 5-7This just initializes all the semaphores. It is the only time anything other than a  down   or an  up  @operation may be done to them.   lline 10Since the buffer is not accessed while the item is produced, we don't need to put semaphores around %@ this part.  4 qlines 11-13Depositing an item into the buffer, however, does require that the producer process obtain exclusive @haccess to the buffer. First, the producer checks that there is an empty slot in the buffer for the new 0JT|item and, if not, waits until there is ( down ( empty ) ). When there is, it waits until it can obtain zexclusive access to the buffer ( down ( mutex ) ). Once both these conditions are met, it can safely @deposit the item.  s tlines 14-15As the producer is done with the buffer, it signals that any other process needing to access the buffer P@may do so ( up ( mutex ) ). It then indicates it has put another item into the buffer ( up ( full ) ). HHˆAh`HHˆ_eaa ldAee HHˆAcHHˆ  e   mlines 18-20Extracting an item from the buffer, however, does require that the consumer process obtain exclugsive access to the buffer. First, the consumer checks that there is a slot in the buffer with an item 0deposited and, if not, waits until there is ( down ( full ) ). When there is, it waits until it can obtain zexclusive access to the buffer ( down ( mutex ) ). Once both these conditions are met, it can safely @extract the item. E mlines 21-22As the consumer is done with the buffer, it signals that any other process needing to access the Qxbuffer may do so ( up ( mutex ) ). It then indicates it has extracted another item into the buffer @&( up ( empty ) ). l eline 23Since the buffer is not accessed while the item is consumed, we don't need to put semaphores x@around this part. Q` HHˆAcHHˆbhdd ldAhh HHˆAfHHˆ//h  `First Readers Writers Problem ,` Introduction `LThis algorithm uses semaphores to solve the first readers-writers problem. V` Algorithm h`71 var wrt ,  mutex : semaphore; t`,2 readcount :  integer ; `3 begin `4 readcount  := 0; `5 wrt  := 1; `6 mutex  := 1; `7 parbegin `,8 repeat (* reader process *) `9(* do something *) `'10 down ( mutex ); `611 readcount  :=  readcount  + 1;  `512 if   readcount  = 1  then !`&13 down ( wrt ); "`%14 up ( mutex ); #`15(* read the file *) $$`, 16 down ( mutex ); %`617 readcount  :=  readcount  - 1; &`518 if   readcount  = 0  then '`$19 up ( wrt ); (`%20 up ( mutex ); )`!21 (* do something else *) *`22 until  false; +`-23 repeat (* writer process *) ,`24(* do something *) -`%25 down ( wrt ); .`26(* write to the file *) /`#27 up ( wrt ); 0`28(* do something else *) 1`29 until  false; 2`30 parend ; 3`31 end . 4` Comments 5 zlines 1-2Here,  readcount  contains the number of processes reading the file, and  mutex  is a semaphore cused to provide mutual exclusion when  readcount  is incremented or decremented. The sema0Ulphore  wrt  is common to both readers and writers and ensures that when one writer is accessing the @-file, no other readers or writers may do so. 6. lines 4-6:wThis just initializes all the semaphores. It is the only time anything other than a  down  or an  up  .noperation may be done to them. As no readers are yet reading the file,  readcount  is initialized to @0 . 7a`^line 9Since the file is not accessed here, we don't need to put semaphores around this part. 8  ulines 10-15Since the value of the shared variable  readcount  is going to be changed, the process must wait P|wuntil no-one else is accessing it ( down ( mutex ) ). Since this process will read from the file, HHˆAfHHˆekgg ldAkk HHˆAiHHˆ  k8mreadcount  is incremented by 1; if this is the only reader that will access the file, it waits until any ~writers have finished ( down ( wrt ) ). It then indicates other processes may access  readcount  @L( down ( mutex ) ) and proceeds to read from the file. 9 xlines 16-20Now the reader is done reading the file (for now.) It must update the value of  readcount  to indizcate this, so it waits until no-one else is accessing that variable ( down ( mutex ) ) and then decre0UQxments  readcount . If no other readers are waiting to read ( readcount  = 0 ), it signals that any reader or writer who wishes to access the file may do so ( up ( wrt ) ). Finally, it indicates it is done @?with  readcount  ( up ( mutex ) ). :l`_line 24Since the file is not accessed here, we don't need to put semaphores around this part. ; lines 25-26The writer process waits ( down ( wrt ) ) until no other process is accessing the file; it then proceeds @to write to the file. < nline 27When the writer is done writing to the file, it signals that anyone who wishes to access the file may P@*do so ( up ( wrt ) ). HHˆAiHHˆhnjj ldAnn HHˆAlHHˆ|..ni `First Readers-Writers Problem  ,` Introduction `^This algorithm uses  SP  and  SV  to solve the first readers-writers problem. jV` Algorithm kh`21 var mutex :  semaphore ; lt`,2 readcount :  integer ; m`3 begin n`%4 readcount  := NREADERS; o`5 mutex  := 1; p`6 parbegin q`.7 repeat (* reader process *) r`8(* do something *) s`/9 SP ( readcount , 1, 1); t`,10 SP ( mutex , 1, 0); u`11(* read the file *) v`-12 SV ( readcount , 1); w`"13 (* do something else *) x`14 until  false; y`/15 repeat (* writer process *) z`16(* do something *) {`M17 SP ( mutex , 1, 1;  readcount , NREADERS, 0) |`18(* write to the file *) }`*19 SV ( mutex , 1); ~` 20(* do something else *) `21 until  false; `22 parend ; `23 end . ` Comments  ylines 1-2Here,  readcount  contains the number of processes not currently reading (or trying to read) the file, @dand  mutex  is a semaphore used to provide mutual exclusion when the file is being written.  lines 3-5This just initializes all the semaphores. It is the only time anything other than a  P  or a  V  operation ªomay be done to them. As no readers are yet trying to read the file,  readcount  is initialized to the U$@>number of reader processes (the constant  NREADERS ). ݪ ylines 7-8This first  repeat  loop contains the code for a reader process. Since the file is not accessed here, 验@2we don't need to put semaphores around this part.  lines 9-11First we atomically decrement  readcount  by  1 , since a process is trying to read the file. We then tcheck that no writers are writing to the file by testing mutex. Note the value of  mutex  is  not  C@ changed.  pline 12Now the reader is done reading the file (for now.) It signals that one less reader is (trying to) read +@=the file by incrementing  readcount  by  1 . : vlines 15-16This second  repeat  loop contains the code for a writer process. Since the file is not accessed F@8here, we don't need to put semaphores around this part.  U nlines 17-18The writer process waits until two conditions are met simultaneously: no other writers are accessaing the file (so  mutex  is  1 , or false) and no readers are accessing the file (so  readcount  is  NREADTwERS ). It then atomically sets  mutex  to 0 (or true), indicating a writer process is accessing the file, B@but does not change readcount. HHˆAlHHˆkqmm ldBqq HHˆBoHHˆq  nline 19When the writer is done writing to the file, it signals that anyone who wishes to access the file may P@8do so by making  mutex   1 , or false. HHˆB oHHˆntpp ldB tt HHˆB rHHˆ(''t^ `General Priority Problem  ,` Introduction ' This uses  SP  and  SV  to solve the general priority problem, in which many different processes each with a different I@5priority is attempting to gain access to a resource. b` Algorithm (t`51 var resource :  semaphore ; `U2 prisem :  array [1..NUMPROCS]  of   semaphore ; `3 begin `4 resource  := 1; `K5 for ( i  = 1;  i  <= NUMPROCS;  i ++) `)6 prisem [ i ] := 1; `>7 repeat (* the  numproc 'th process *) `8(* do something *) `>9 SP ( prisem [ numproc ], 1, 1); `-10 SP ( resource , 1, 1; `T11  prisem [0], 1, 0; ;  prisem [ numproc -1], 1, 0); ` 12(* access the resource *) `513 SV (resource, 1; prisem[numproc], 1); `14(* do something else *) `15 until  false; `16 `17 end.  M` Comments !_ lines 1-2Here,  resource  is 1 when the resource is not being used, and  prisem [ i ] is 1 when process  i  does not kowant access to the resource. We assume that the lower the index into  prisem , the higher the process @ priority. " lines 3-6This just initializes all the semaphores. It is the only time anything other than an  SP  or an  SV  operyation may be done to them. As the resource is not yet assigned,  resource  is set to  1  (false); as no hU*@tprocess wants access to it, each semaphores  prisem [ i ]  are also set to  1  (false). # olines 7 onA liberty with notation now; this loop is replicated in each process. We will assume that the vari@mable  procno  contains the number of the current process (that is, the index into  prisem ). $Ȫ`bline 8Since the resource is not accessed here, we don't need to put semaphores around this part. %U_ lines 9-12First we atomically decrement  prisem [ numproc ]  by  1 , to indicate that this process wishes to gain 㪍aaccess to the resource. We then check atomically (and simultaneously) that no other process has 0Tjaccess, and that no process with a higher priority is waiting for access. If these are both true, access @kto the resource is granted, so  resource  is set to  0  (false), and the process proceeds. &  vline 13Now the process is done accessing the resource (for now.) It signals that by setting both  resource  @Kand the appropriate element of the semaphore array to  1  (false). Q %` HHˆB rHHˆqwss ldB4ww HHˆB5uHHˆg~wQ `send/receive Chart R,` Introduction S pThese charts summarize the actions of the send and receive primitives using both blocking and non-blocking mode I@"and explicit and implicit naming. Tb`Charts ^tBhOThis chart summarizes how naming and blocking affects the send primitive. h쪢BhRThis chart summarizes how naming and blocking affects the receive primitive. Qi]` HHˆB7uHHˆtzvv ldB8zz HHˆB9xHHˆ^,,zj `Producer Consumer Problem k,` Introduction l qThis algorithm uses blocking send and receive primitives to solve the producer/consumer (or bounded-buffer) probI@Mlem. In this solution, the buffer size depends on the capacity of the link. mb` Algorithm nt`/1 var  nextp, nextc : item; o`+2 procedure   producer ; p`3 begin q`14 while   true   do begin r`+5(* produce item in  nextp  *) s`C6 send ( Consumerprocess ,  nextp ); t`7 end ; u` 8 end; v`&9 procedure  consumer ; w`10 begin x`211 while   true   do begin y`G12 receive ( Producerprocess ,  nextc ); z`,13(* consume item in  nextc  *) {`14 end ; |`15 end; }` 16 begin ~`17 parbegin `518 Consumerprocess :  consumer ; `519 Producerprocess :  producer ; `20 parend ` 21 end . }` Comments  xline 1Here,  nextp  is the item the consumer produces, and  nextc   the item that the consumer con@sumes.  jlines 2-8This procedure simply generates items and sends them to the consumer process (named  Consumqerprocess ). Suppose the capacity of the link is n items. If  n  items are waiting to be consumed, 2@yand the producer tries to  send  the  n +1-st item, the producer will block (suspend) until the consumer lhas removed one item from the link (i.e., done a  receive  on the producer process). Note the name cof the consumer process is given explicitly, so this is an example of explicit naming or direct icommunication. Also, since the  send  is blocking, it ias an example of synchronous communica@tion.  klines 9-15This code simply receives items from the producer process (named  Producerprocess ) and  bconsumes them. If when the receive statement is executed there are no items in the link, the con0 @psumer will block (suspend) until the producer has put an item from the link (i.e., done a  send  to the `consumer process). Note the name of the producer process is given explicitly; again this is an nexample of explicit naming or direct communication. Also, since the  receive  is blocking, it is @+an example of synchronous communication. L`slines 17-20This starts two concurrent processes, the  Consumerprocess  and the  Producerprocess . Q` HHˆB;xHHˆw}yy ldBX}} HHˆBY{HHˆ‚//}  `Producer Consumer Problem  ,` Introduction  `[This algorithm uses a monitor to solve the producer/consumer (or bounded-buffer) problem.  V` Algorithm h`#1 buffer : monitor ; t`X2 var  slots :  array  [0.. n -1]  of  item; `<3 count ,  in ,  out : integer; `74 notempty ,  notfull : condition; `P5 procedure   entry   deposit ( data : item); ` 6 begin `97 if   count  =  n   then `'8 notfull . wait ; $`: 9 slots [ in ] :=  data ; `A10 in  :=  in  + 1  mod   n ; `-11 count  :=  count  + 1; `*12 notempty . signal ; `13 end ; `_14 procedure   entry   extract ( var   data : item); `15 begin `016 if   count  = 0  then `)17 notempty . wait ; $`< 18 data  :=  slots [ out ];  `C19 out  :=  out  + 1  mod   n ; !`-20 count  :=  count  1; "`)21 notfull . signal ; #`22 end ; $`23 begin %`B24 count  := 0;  in  := 0;  out  := 0; &`25 end . '` Comments ( lines 2-4Here,  slots  is the actual buffer,  count  the number of items in the buffer, and  in  and  out  the lindices of the next element of  slots  where a deposit is to be made or from which an extraction is 0U"cto be made. There are two conditions we care about: if the buffer is not full (represented by the mcondition variable  notfull ), and if the buffer is not empty (represented by the condition variable @notempty ). ) sline 5The keyword  entry  means that this procedure may be called from outside the monitor. It is called Uby placing the name of the monitor first, then a period, then the function name; so, 6T@'buffer . deposit () . * plines 7-8This code checks to see if there is room in the buffer for a new item. If not, the process blocks on %gthe condition  notfull ; when some other process does extract an element from the buffer, then 0&ithere will be room and that process will signal on the condition  notfull , allowing the blocked bone to proceed. Note that while blocked on this condition, other processes may access procedures @within the monitor. +X plines 9-11This code actually deposits the item into the buffer. Note that the monitor guarantees mutual exclud@sion. ,s jline 12Just as a producer will block on a full buffer, a consumer will block on an empty one. This indiPccates to any such consumer process that the buffer is no longer empty, and unblocks exactly one of HHˆB[{HHˆz|| l}HHBbuHHvBWU&`send }Bdu~vBWV` blocking }VBfuVvBWW` non-blocking }HHBhuHHvGX explicit P@naming }BjuvGY -send message to receiver; wait until message P@ accepted }VBluVvGWZ`send message to receiver }HHBnuHHvH[ implicit P@naming }BpuvH\ ,broadcast message; wait until all processes P@accept message }VBruVvHW]`broadcast message }HCHBvuHCHvIW_&`receive }CBxu CvIW`` blocking }VCBzu VCvIWa` non-blocking }HWHB|u HWHvJb explicit P@naming }WB~u WvJWc`#wait for message from named sender }VWBu VWvJd -if there is a message from the named sender, P@get it; otherwise, proceed }HwHBu HwHvKe implicit P@naming }wBu wvKWf`!wait for message from any sender }VwBuVwvKg /if there is a message from any sender, get it; P@otherwise, proceed dB HHˆBHHˆ,@Gthem. If there are no blocked consumers, this is effectively a no-op. - Sline 14As with the previous procedure, this is called from outside the monitor by @'buffer . extract () . . slines 16-17 This code checks to see if there is any unconsumed item in the buffer. If not, the process blocks on fthe condition  notempty ; when some other process does deposit an element in the buffer, then 0UPathere will be something for the consumer to extract and that producer process will signal on the jcondition  notempty , allowing the blocked one to proceed. Note that while blocked on this condi@@tion, other processes may access procedures within the monitor. /o klines 18-20This code actually extracts the item from the buffer. Note that the monitor guarantees mutual {@ exclusion. 0 jline 21Just as a consumer will block on an empty buffer, a producer will block on a full one. This indibcates to any such producer process that the buffer is no longer full, and unblocks exactly one of oUJ@Gthem. If there are no blocked producers, this is effectively a no-op. 1`-lines 23-25This is the initialization part. Q2UE` HHˆBHHˆ} ldB HHˆBHHˆ|//) `First Readers Writers Problem *,` Introduction +`LThis algorithm uses a monitor to solve the first readers-writers problem. ,V` Algorithm -h`(1 readerwriter :  monitor .t`*2 var readcount : integer; /`!3 writing : boolean; 0`94 oktoread ,  oktowrite : condition; 1`-5 procedure entry  beginread ; 2`6 begin 3`47 readcount  :=  readcount  + 1; 4`-8 if   writing   then 5`(9 oktoread . wait ; 6`10 end ; 7`;11 procedure   entry   endread ; 8`12 begin 9`513 readcount  :=  readcount  - 1; :`414 if   readcount  = 0  then ;`,15 oktowrite . signal ; <`16 end ; =`>17 procedure   entry   beginwrite ; >`18 begin ?`S19 if   readcount  > 0  or   writing   then @`*20 oktowrite . wait ; A` 21 writing  := true; B` 22 end ; C`<23 procedure   entry   endwrite ; D`(24 var  i : integer; E`25 begin F`!26 writing  := false; G`427 if   readcount  > 0  then H`A28 for   i  := 1  to   readcount I`,29 oktoread . signal ; J`30 else K`+31 oktowrite . signal ; L`32 end ; M`33 begin N`;34 readcount  := 0;  writing  := false; O`35 end . P` Comments Q+ |lines 1-4Here,  readcount  contains the number of processes reading the file, and  writing  is true when a 7swriter is writing to the file.  Oktoread  and  oktowrite  correspond to the logical conditions of U@Ebeing able to access the file for reading and writing, respectively. RR ulines 7-9In this routine, the reader announces that it is ready to read (by adding 1 to  readcount ). If a ^lwriter is accessing the file, it blocks on the condition variable  oktoread ; when done, the writer @Dwill signal on that condition variable, and the reader can proceed. QSy vlines 13-15In this routine, the reader announces that it is done (by subtracting 1 from  readcount ). If no HHˆBHHˆ ldB HHˆBHHˆ  Semore readers are reading, it indicates a writer may go ahead by signalling on the condition variable @oktowrite . T {lines 19-21In this routine, the writer first sees if any readers or writers are accessing the file; if so, it waits until mthey are done. Then it indicates that it is writing to the file by setting the boolean  writing  to @ true . UH lines 26-31Here, the writer first announces it is done by setting  writing  to  false . Since readers have priThority, it then checks to see if any readers are waiting; if so, it signals all of them (as many readers JUO@Ncan access the file simultaneously). If not, it signals any writers waiting. Vo`(line 34This initializes the variables. QWUJ` HHˆBHHˆ ldB HHˆBHHˆ//X `Monitors and Semaphores Y,` Introduction Z sThis handout describes how to express monitors in terms of semaphores. If an operating system provided semaphores I@Tas primitives, this is what a compiler would produce when presented with a monitor. [b` Algorithm \t`U1 var mutex ,  urgent ,  xcond :  semaphore ; ]`D2 urgentcount ,  xcondcount :  integer ; ^`?The body of each procedure in the monitor is set up like this: _`%3 down ( xmutex ); ``4(* procedure body*) a`45 if   urgentcount  > 0  then b`#6 up ( urgent ) c` 7 else d`#8 up ( mutex ); e`EEach  x . wait  within the procedure is replaced by: f`59 xcondcount  :=  xcondcount  + 1; g$`: 10  if  urgentcount  > 0  then h`) 11 up ( urgent ) i` 12 else j`$13 up ( mutex ); k`%14 down ( xcond ); l`615 xcondcount  :=  xcondcount  - 1; m`GEach  x . signal  within the procedure is replaced by: n`816 urgentcount  :=  urgentcount  + 1; o$`? 17  if  xcondcount  > 0  then begin p`, 18 up ( xcondsem ); q`'19 down ( urgent ); r`20 end ; s`821 urgentcount  :=  urgentcount  - 1; t` Comments u |line 1The semaphore  mutex  is initialized to  1  and ensures that only one process at a time is executing kwithin the monitor. The semaphore  urgent  is used to enforce the requirement that processes that `fsignal  (and as a result are suspended) are to be restarted before any new process enters the monuitor. The semaphore  xcond  will be used to block processes doing  wait s on the condition variable ix . Note that if there is more than one such condition variable, a corresponding semaphore for each @qcondition variable must be generated. Both  urgent  and  xcond  are initialized to  0 . v vline 2The integer  urgentcount  indicates how many processes are suspended as a result of a  signal   moperation (and are therefore waiting on the semaphore  urgent ); the counter  xcondcount  is 0Bkassociated with the condition variable  x , and indicates how many processes are suspended on that @Hcondition ( i.e. , suspended on the semaphore  xcond ). w1 mlines 3-8Since only one process at a time may be in the monitor, the process entering the monitor procedure =zmust wait until no other process is using it ( down ( mutex ) ). On exit, the process signals others 0ethat they may attempt entry, using the following order: if any other process has issues a signal and been suspended ( i.e. ,  urgentcount  _  0 ), the exiting process indicates that one of those is to be xcontinued ( up ( urgent ) ). Otherwise, one of the processes trying to enter the monitor may do so @&( up ( mutex ) ). Qx| lines 9-15First, the process indicates it will be executing an  x . wait  by adding  1  to  xcondcount . It then HHˆBHHˆ ldC? HHˆC@HHˆ{  xesignals some other process that that process may proceed (using the same priority as above). It sus|pends on the semaphore  xcond . When restarted, it indicates it is done with the  x . wait  by sub0tracting  1  from  xcondcount , and proceeds. Note that the  down ( xcond )  will always suspend the process since, unlike semaphores, if no process is suspended on  x . wait , then  x . signal  is @fignored. So when this is executed, the value of the semaphore  xcond  is always  0 . yE lines 16-21First, the process indicates it will be executing an  x . signal  by adding  1  to  urgentcount . It Qthen checks if any process is waiting on condition variable  x  ( xcondcount  >  0 ), and if so signals 0 any such process ( up ( xcondsem ) ) before suspending itself ( down ( urgent ) ). When restarted, @ithe process indicates it is no longer suspended (by subtracting  1  from  urgentcount ). Qzx` HHˆCBHHˆ! ldD!! HHˆDHHˆ!!!{ `Monitors and Priority Waits |,` Introduction } tThis is an example of a monitor using priority waits. It implements a simple alarm clock; that is, a process calls 'Ialarmclock . wakeme ( n ) , and suspends for  n  seconds. Note that we are assuming the hardware invokes the proW@8cedure  tick  to update the clock every second. ~n` Algorithm `'1 alarmclock : monitor ; `)2 var  now :integer; `"3 wakeup : condition; `T 4 procedure   entry   wakeme ( n : integer); `5 begin `;6 alarmsetting  :=  now  +  n ; `H 7 while   now  <  alarmsetting   do `>8 wakeup . wait ( alarmsetting ); `'9 wakeup . signal ; ` 10 end ;  `811 procedure   entry   tick ;  `12 begin  `)13 now  :=  now  + 1;  `(14 wakeup . signal ;  `15 end . A` Comments S ~lines 2-3Here,  now  is the current time (in seconds) and is updated once a second by the procedure  tick . _@NWhen a process suspends, it will do a wait on the condition  wakeup . n`Fline 6This computes the time at which the process is to be awakened. `\lines 7-8The process now checks that it is to be awakened later, and then suspends itself.  pline 9Once a process has been woken up, it  signal s the process that is to resume next. That process pchecks to see if it is time to wake up; if not, it suspends again (hence the  while  loop above, rather &@^than an  if  statement). If it is to wake up, it  signal s the next process  gline 14This is done once a second (hence the addition of 1 to now). The processes to be woken up are kqueued in order of remaining time to wait with the next one to wake up first. So, when  tick  sigp̪knals, the next one to wake up determines if it is in fact time to wake up. If not, it suspends itself; if @so, it proceeds. HHˆDHHˆ$  ldI$$! HHˆI"HHˆ‡22$= `First Readers Writers Problem @,` Introduction z`KThis uses crowd monitors to solve the first readers/writers problem.  BV` Algorithm Ah`81 readerwriter :  crowd   monitor Ct`?2 var Readers :  crowd   read ; D`H3 Writers :  crowd   read ,  write ; E`,4 readcount :  integer ; F`*5 writing :  boolean ; G`B6 oktoread ,  oktowrite :  condition ; H`87 guard procedure entry   beginread ; I`8 begin J`49 readcount  :=  readcount  + 1; K`.10 if   writing   then L`)11 oktoread . wait ; M`(12 enter   Readers ; N`13 end ; O`714 guard procedure entry   endread ; P`15 begin Q`(16 leave   Readers ; R`517 readcount  :=  readcount  - 1; S`418 if   readcount  = 0  then T`,19 oktowrite . signal ; U`20 end ; V`:21 guard procedure entry   beginwrite ; W`22 begin X`S23 if   readcount  > 0  or   writing   then Y`*24 oktowrite . wait ; Z` 25 writing  := true; [`(26 enter   Writers ; \`27 end ; ]`828 guard procedure entry   endwrite ; ^`229 var  i :  integer ; _`30 begin ``(31 leave   Writers ; a`!32 writing  := false; b`433 if   readcount  > 0  then c`<34 for   i  := 1  to  readcount d`,35 oktoread . signal ; e`36 else f`,37 oktowrite . signal ; g`38 end ; h`.39 procedure entry   read ; i`*40  read from shared data  j`41 end ; k`/42 procedure entry   write ; l`)43  write to shared data  m`44 end ; n`45 begin Ao`;46 readcount  := 0;  writing  := false; HHˆI"HHˆ!'##  ldI''" HHˆI%HHˆ 'p`47 end . q` Comments r jlines 2-3These lines define which procedures can be called by members of the crowd; here, members of the Readers  crowd can call  read , and members of the  Writers  crowd can call either  read  or  write . Only 2Jzprocesses in those crowds can call  read  or  write ; should any other process do so, it will cause a run-@ time error. sd qline 7The keyword  guard  means this procedure is mutually exclusive (so only one process at a time may pfbe in the guarded procedures). Note this relaxes the definition of Hoares monitor, in that multiple |@4proceses may now access the monitor simultaneously. t`vline 12This puts the calling process into the  Readers  crowd; it may now call the procedure  read . u line 16This removes the calling process from the  Readers  crowd, so it may not call  read  until after it calls @+beginread  and executes line 12 again. v` line 26This puts the calling process into the  Writers  crowd; it may now call the procedures  read  and  write . w line 31This removes the calling process from the  Readers  crowd, so it may not call  read  or  write  until after Ъ@Xit calls  beginread  or  beginwrite  and executes lines 12 or 26 again. xߪ`\line 39Now any number of processes may access the  read  procedure simultaneously. yǪ mline 42Although it may appear that any number of processes may access the  write  procedure simultamneously, note that all callers must first have invoked  beginwrite  and only one such process will PE@Hbe active at a time. So at most one process will call  write . HHˆI%HHˆ$*&& ldI**# HHˆI(HHˆU***{ `Producer Consumer Problem |,` Introduction 7`HThis uses invariant expressions to solve the producer consumer problem. 6V` Algorithm }h`11 buffer :  invariant module ; ~t`'2 const   n  = 1024; `b3 var  slots :  array  [0.. n -1]  of   item ; `34 in ,  out : 0.. n -1; `$5 invariant   deposit `\6 StartCount ( deposit ) -  FinishCount ( extract ) < n; `37 CurrentCount ( deposit ) = 0; `$8 invariant   extract `[9 StartCount ( extract ) -  FinishCount ( deposit ) < 0 `410 CurrentCount ( extract ) = 0; `Q11 procedure entry   deposit ( data :  item ); `12 begin  `613 slots [ in ] :=  data ;  `A14 in  :=  in  + 1  mod   n ;  `15 end ;  `_16 procedure entry   extract ( var   data :  item );  `17 begin `718 data  :=  slots [ out ]; `C19 out  :=  out  + 1  mod   n ; `20 end ; `21 begin `,22 in  := 0;  out  := 0; `23 end . ` Comments  lines 3-4Here,  slots  is the actual buffer and  in  and  out  the indices of the next element of slots where a deposit @9is to be made or from which an extraction is to be made. `Fline 5The next constraints apply to the procedure  deposit . ™ |line 6This invariant checks that there is at least one slot in the buffer that is empty. If false, then  deposit  Ѫ@Xmust have been started at least  n  times more than  extract  finished. ઍ`bline 7This ensures at most one process can be in  deposit  at a time (mutual exclusion). ÛUb`Fline 8The next constraints apply to the procedure  extract .  |line 6This invariant checks that there is at least one slot in the buffer that is full. If so, then  deposit  fin @1ished more times than  extract  started. `bline 7This ensures at most one process can be in  extract  at a time (mutual exclusion). . `zline 11As with the previous procedure, this is called from outside the monitor by  buffer . extract ().  nlines 12-15 This code actually extracts the item from the buffer. Note that the invariant guarantees mutual C@ exclusion. QR`-lines 23-25This is the initialization part. HHˆI(HHˆ'-)) ldI--$ HHˆI +HHˆ- `First Readers Writers Problem  ,` Introduction 9`LThis uses invariant expressions to solve the first readers writers problem. 8V` Algorithm !h`;1 readerwriter :  invariant   module "t`!2 invariant   read #`13 CurrentCount ( write ) = 0; $`"4 invariant   write %`Z5 CurrentCount ( write ) +  CurrentCount ( read ) = 0; &`-6 procedure entry   read ; '`(7  read from shared data  (`8 end ; )`.9 procedure entry   write ; *`(10  write to shared data  +`11 end ; ,`12 begin -`13 end . /` Comments .# zlines 2-3This states the condition that must hold whenever the procedure  read  is executed; it requires that no /oprocesses be executing  write . Note this means readers will have priority over writers when a reader 0U:eis presently reading; it says nothing about what happens if a reader and a writer call the module at @the same time. 0V xlines 4-5This states the condition that must hold whenever the procedure  write  is executed; it requires that b@Dno processes be executing either  read  or  write . 1q`Alines 6-11Here, the routines simply do the reading and writing. 2쪶`hlines 12-13The initialization part of the module; as there are no variables in it, this part is empty. A?` HHˆI"+HHˆ*0,,  ldI#00% HHˆI$.HHˆ %%0> `Producer Consumer Problem  ,` Introduction 3`oThis algorithm uses open path expressions (in the form of Path Pascal) to solve the producer/consumer problem. 4V` Algorithm 5h`71 type   buffer :  object ; :t`]2 path   n :(1:( deposit ); 1:( extract ))  end ; ;`c3 var  slots :  array  [0.. n -1]  of   item ; <`54 in ,  out :  integer ; =`Q5 procedure entry   deposit ( data :  item ); >`6 begin ?`67 slots [ in ] :=  data ; @`A8 in  :=  in  + 1  mod   n ; A`9 end ; B``10 procedure entry   extract ( var   data :  item ); C`11 begin D`812 data  :=  slots [ out ]; E`D13 out  :=  out  + 1  mod   n ; F`14 end ; G`15 begin H`-16 in  := 0;  out  := 0; I`17 end . JA` Comments KS lines 1-2:This construct says that at most one invocation of  deposit  or one invocation of  extract  can run con_currently ( 1:() ), that for every call to  extract  at least one call to  deposit  must have returned, and 0U2wthat the difference between the number of calls to  deposit  and the number of calls to  extract  must @ never be more than  n . L lines 3-4:Here,  slots  is the actual buffer, and  in  and  out  the indices of the next element of  slots  where a cdeposit is to be made or from which an extraction is to be made. Note that we need not keep track 0feof how many slots of the buffer contain something; the path constraint above ensures that neither an @Wextraction from an empty buffer nor insertion into a full buffer will ever take place. M pline 5:This function is called by placing the name of the object first, then a period, then the function name; Ū@+so,  buffer . deposit (). NԪ klines 7-8:This code actually deposits the item into the buffer. Note that the path expression guarantees ઍ@mutual exclusion. O戴`Iline 10:Again, this is called by  buffer . extract (). Pȫ lline 14:This code actually extracts the item from the buffer. Again,the path expression guarantees mutual P @ exclusion. HHˆI&.HHˆ-3// ldI33& HHˆI1HHˆ3   dProducer Consumer Process Z,d Introduction [dGThis uses Hoares CSP language to solve the producer consumer problem. ]Vd Algorithm chdBThis process manages the buffer; call it  boundedbuffer . dtd,1 buffer : (0..9)  item ; fd32 in ,  out :  integer ; gd3 in  := 0; d4 out  := 0; d5*[ in  <  out  +  n ;  producer  ?  buffer ( in   mod   n ) d16 n   in  :=  in  + 1 dV7     out  <  in ;  consumer  ?  more () db8 n   consumer  !  buffer ( out   mod   n ); d)9  out  :=  out  + 1 d10 ] d Comments  $ lines 1-2:Here,  buffer  is the buffer,  in  the number of items put into the buffer, and  out  the number of items DUextracted. The producer process outputs an item  nextp  to this process by: &d1bounded - buffer  !  nextp ; dNand the consumer process outputs an item  nextc  to this process by: dibounded - buffer  !  more ();  bounded - buffer  ?  nextc ;  dS( more () is there because CSP does not allow output commands in guards.) !dBlines 3-4:These just initialize  in  and  out . "$lines 5-6:If there is room for another item in the buffer ( in  <  out  +  n ), wait for the producer to produce some}thing and deposit it in an empty buffer slot ( producer  ?  buffer ( in   mod   n )) and indicate that slot is P\D-now used ( in  :=  in  + 1). #$lines 7-9:If the buffer is full ( out  <  in ), wait until the consumer asks for something ( consumer  ?  more ()), then output the next element of the buffer ( consumer  !  buffer ( out   mod   n )), and indicate it has been P; D0extracted ( out  :=  out  + 1). HHˆI1HHˆ0622 ldJ 66' HHˆJ 4HHˆ‚//6!& `Producer Consumer Problem ',` Introduction (`TThis algorithm uses ADA to solve the producer/consumer (or bounded-buffer) problem. )V` Algorithm *h`0This process (task, to ADA) manages the buffer. +t`21 task   boundedbuffer   is ,`T2 entry   deposit ( data :  in   item ); -`U3 entry   extract ( data :  out   item ); .`4 end ; /`A5 task   body   boundedbuffer   is 0`U6 buffer :  array [0.. n -1]  of   item ; 1`L7 count :  integer   range  0.. n  := 0; 2`Z8 in ,  out :  integer   range  0.. n -1 := 0; 3`9 begin 4`10 loop 5`11 select 6`712 when   count  <  n  => 7``13 accept   deposit ( data :  in   item )  do 8`;14 buffer [ in ] :=  data ; 9`15 end ; :`F16 in  := ( in  + 1)  mod   n ; ;`017 count  :=  count  + 1; <`:18 or   when   count  > 0 => =`a19 accept   extract ( data :  out   item )  do >`<20 data  :=  buffer [ out ]; ?`21 end ; @`H22 out  := ( out  + 1)  mod   n ; A`023 count  :=  count  - 1; B`24 end select ; C`25 end loop ; D`26 end . E`3The producer deposits an item into the buffer with F`A27 boundedbuffer . deposit ( nextp ); G`7and the consumer extracts an item from the buffer with H`A28 boundedbuffer . extract ( nextc ); I` Comments J ylines 1-4This indicates that the procedures  deposit  and  extract  may be called outside the task, and @Xthat  extract  will return something in its parameter list (the  out ). K lines 6-8As usual,  buffer  is the buffer, and  count  the number of items currently in the buffer;  in  and "@Wout  are the indices indicating where deposits go or where extractions come from. L1 lines 13-17If there is room in the buffer ( when   count  <  n ) this process will accept a request to deposit an =@Witem in it ( accept   deposit   ); it then updates its variables. ML lines 18-23If there is an item in the buffer ( when   count  > 0 ) this process will accept a request to extract an Xyitem from the buffer ( accept   extract   ); the item is returned via the parameter list. This pro+U@#cedure then updates its variables. Ns tline 24If both of the above two  when  conditions are true, and both a producer and consumer has invoked a Pfprocedure named by an  accept  statement (called an open accept statement), the system will HHˆJ4HHˆ3955 ldJ99( HHˆJ7HHˆZ9"Ndselect one to be executed in some fair manner (such as first-come-first-serve). If only one of the kconditions is true, and the procedure named in an  accept  statement in the body of the when state0qment is open, that one will be executed. If both of the  when  conditions are false, an error condition @.occurs (this usually terminates the process.) O` PP` A^` HHˆJ7HHˆ688 l(dLeftd;Rightd ReferenceddHTMLdDHTMLd Headingsd d Fd Id Ld Od Rd WdZd ]d `d cd fd idldodrdudxd{ddddd d!d ""d!#%d"$(d#%+d$&.d%'1d &(4d!'7@@ QMapping Table Title. @@ QBody. f@   .$.H.l..... .D.h.CodeN. Hf@ QH.. CodeComment. @@ QFooter. f@T Q TableTitleT:Table : . Hf@ QH.. CodeComment. f@ QCellBody. f@ QCellBody. ~f@  ~.....2.V.z...CodeC. ~f@   ~.....2.V.z...CodeC. ~f@   ~.....2.V.z...CodeC. f@ Q .$.H.l..... .D.h.CodeN. f@ Q .$.H.l..... .D.h.CodeN. f@ QCellBody. f@ QBody. @@ QHeader Double Line. f@ Q CellFooting. f@ Q CellHeading. f@ Q CellBody. @@ QMapping Table Cell. f@ Q&CellBody. @@/Mapping Table Cell. @@ /Mapping Table Cell. @@ QMapping Table Cell. Hf@ QH.. CodeComment. f@ QBody.  f@PQTitleBody. f@ Q BodySpaced. f@ Q Bulleted\t. f@ Q...Date. mf@ Ql. DateProject. @@ QHeader Double Line. f@T QHeading1Body. f@ Q NumberedSpaced.\t. f@ Q.Reading. f@ Q H.l..... .D.h...Body. f@$Q.Line Single Line. f@ Q CellHeading. f@ Q Footnote. f@T QHeading2Body. f@T Q HeadingRunInBody. f@ Q Indented. f@ Q TableFootnote. f@T Q TableTitleT:Table : . L̀Lf@N Q Numbered N:.< =1>. $f@L Q$. Lettereda L:.. $f@L Q$. LetteredL:.. f@T QHeading2Body.  f@T QHeading1Body. f@ Q .$.H.l..... .D.h...Body. f@ QBody. f@ Q-.Body. Hf@ QH. LineComment. f@ Q~Body. f@NE Q Numbered1 N:.Numbered. $f@L Q$. Lettereda L:.. $f@L Q$. LetteredL:.. f@ QBody. L̀Lf@N Q Numbered N:.< =1>. f@ )  .$.6.H.Z.l.~....... .D.h...Body. f@ QBody.  f@PQTitleBody.  f@PQTitleBody. %f@ Q BodyIndent. f@  $.6.Z.u..CodeASM. Q Q Q Q / Q ڝQQEmphasis )  X WingdingX  WingdingQEquationVariables ڝQ /   BoldItalic QItalic QBold Q/ Q  ComputerQ Q )  Q    Q    Computer    Computer Q   Q Subscript  Subscript   Computer  Computer Q   Q M SymbolM Symbol Q Superscript  Superscript Q Zd Z ZdZdThinMediumDoubleThick@ Very Thin HHHHHFormat A HHHHHFormat AH Mapping Table HHHHHFormat BH Mapping Table h*|#HHHHHf$*DHH+5?HH&69?HH :C?HHH DF?HH*6 ? @ h( A B C D E h  F G H I J h  K L M N O h  P Q R S T h( UVWXYh Z[\]^h_`abc7h defghChijklm]h(nopqrh stuvwh xyz{|h(}~h h    h  h h h)h  !"#$5h%&'()Oh  *+,-.[h!/ 0 1 2 3 uh "4!5!6!7!8!h!#9":";"<"="©h ">#?#@#A#B#» %C$D$E$ $&F%G%H% %'I&J&K& &(L'M'N'')O(P(Q(((*FR)S)T)D )FU*V*W*V ,FX+Y+Z+f +-F[,\,],r ,.F^-_-`-~ -/Fa.b.c..0Fd/e/f//1Fg0h0i002Fj1k1l113Fm2n2o224Fp3q3r3 35Fs4t4u4& 4Fv5w5x58 7Fy6z6{6H 68F|7}7~7T79F888n 8F999 ;F:::: :CF ;";#;$; =  <<<<> ====? >>>K >@ ???W ?A @@@c @ AAAHGv~BBB ;F%C&C'C(C EF)D,D-D DFF.E/E0E EF1FBFCFHBHvGGGHGvHHHHC JvII IHW IKv J J JHw Jv KKKComment ;C ;G d BlackT!WhiteddARedddGreendd BluedCyandMagentad Yellowd PICT Color 1Header/Footer $1Header/Footer $1Header/Footer $2Header/Footer $2IndexIndexCommentCommentSubjectSubjectAuthorAuthorGlossaryGlossaryEquationEquation Hypertext Hypertext  Cross-Ref Cross-Ref Conditional TextConditional TextPositionFMPrivatePositionFMPrivateRangeEndFMPrivateRangeEndFMPrivate HTML Macro HTML Macro M.Times.P Times-Roman FrameRoman M.Courier.PCourier FrameRoman M.Times.B Times-Bold FrameRoman M.Courier.B Courier-Bold FrameRoman M.Times.I Times-Italic FrameRoman M.Helvetica.BHelvetica-Bold FrameRoman M.Geneva.PGeneva FrameRoman M.Wingdings.P Wingdings FrameRoman FrameRomanM.Helvetica.BIHelvetica-BoldOblique FrameRoman M.Times.BITimes-BoldItalic FrameRoman FrameRoman M.Courier.ICourier-Oblique FrameRoman M.Courier.BICourier-BoldOblique FrameRoman M.Symbol.PSymbol FrameRoman FrameRomanbCourier(Geneva. HelveticaLSymbolPTimesW Wingdings!Regular$Roman MediumBoldRegular ObliqueItalic<4} x),` %I_YB*!(=B˝0l4J*Nbhl{ T6jmXy`/zۜ)]4o"!~HNg3غay|YUbu|w&$ek O[*授XCInrHTcTS愉\?`g+W_:O&ۆC)40a<4+Cb ~S6P?L5G^RbJ&o#09[ q0mQ:=/xe`(zqeq