AXIOMATIC PROOF TECHNIQUES + FOR PARALLEL PROGRAMS Susan Speer OwicYi TR 75--H251 July 1975 Departrneflt of Computer Cornell University Ithaca, NY 14853 Science +This research was partially supported by National Science Foundation 9rant GJ-42512. BIOGRAPHICAL SKITCH Susan Speer Owicki was bom on June 25. 1947, in Pittsburgh. Pennsylvania. In June, 1968, she received the Bachelor of Science degreo in `latheratics from `.?ichigan State University, and in Januarv, 1970, the ".?ster of Science degree in Computer Science fro? Cornell University. Her professional experience includes several years of work as a progra=er. She is a member of the Association for Computing `lachinery', Pi 11' ?psilon mathematics honorary. and Phi Beta Xappa. ii ACKNOWLEDC'.?EWrS am deeply indebted to Professor David Gries. my thesis advisor. He was a constant source of encouragement and advice and taught me a great deal about the organization and presentation of Information. Thanks also go to Professors Juris flarti,.annis and James Braable for serving on my special committee, I had many valuable discussions of parallel processing with Professor Charles >ioore and of logic with Professor Robert Constable and Marvin Solo?on. The superb typing of this thesis is the work of `,!rs. Caroline Marold who did much to improve its layout and appearance. Finally, I am very grateful to ny husband Jack for his help and support throughout this research. iii TAB'?E or CONTENTS Page Chapter 1. Introduction 1.1 Introduction 1.2 Outline of the Thesis s Chapter 2. Se?uentia1 Progra?s 7 2.1 The Scouential Progran6¶ing Language (SL) 7 2.2 The Deductive Serantics a 2.3 The Interpretive ?odel 16 2.4 Consistency of the Deductivo Syate? and tho Interpreter 24 Chapter 3. parallel Prograns 26 3.1 The Gencral parallel Language (GPL) 27 ?.2 The Interpretive o+".odel 30 3.3 The Deductive System 36 3.4 Consistency of the Deductive System and the Interpreter 45 ?.5 Auxiliary Variables 52 3.6 ?jtua1 Exclusion 63 Chapter 4. The Restricted parallel Language CRPL) 71 4.1 The Language 72 4.2 The Ir.terpretiv0 ?odcl 76 4.3 Axiora and Inference Rules 1 4.4 Consistency 93 iv Page Chapter 5. Additional Properties o?. Parallel Progra?.?s 95 5.1 ?Iutual Exclusion 95 5.1.1 C;PL 96 5.2.3 RPL 97 5.2 Rlocking 112 5.2.1 Prograa Blocking in CPL 113 5.2.2 t)cadlock in ?PL 122 5.2.3 Program Blocking in RPL 124 5.2.4 Auxiliary Variables 132 5.3 Termination 133 Chapter 6. Consistency and Completeness of the Deductive System 136 6.1 Consiatcncy 13? 6.2 Completcncss 149 6.2.1 The Program T 153 6.2.2 The Functions pre. post and I for T- 164 6.2.3 Assertion Functions 171 6.2.4 lmplications of the gelative Completeness Theore: 132 6.2.5 Proof of Lcrjsa 6.31 135 Chapter 7. Conclusions and Co;r?ents 192 Bibliography 196 v C1iAPT?P I I.\?RODUCTlON 1.1.Introduction. The purpose of this thesis is to present an axiomatic metl?d for Pr0vlnb certain properties of ;?arallel procracs. The most fundar?ntal property is partial correctness: a pro?ram is partially correct if it either co:putes the recuirc? result or fails to terminate. Total correctness includes the requirement that the program terminates. iloare [11o69i has developed axioms and inference rules for proving the partial correctness of sequential progra?s written in an Aleol-like syntax. and with certsin adaptations this deductive system can be used to establish total correetness (.?anna [`1a74]). Its extension to parallel programs (Iloare [Ilo72]) is the basis of the work in this thesis. The importance of correetnesa proofs for seq?iential pro?rams has lon? been recogni?ed. The advocatea of structured programming have argued that a well structured pro:ran should be casy to prove correct. and that progracs should be written with a correctness proof in mind. The need is even greater with parallel programs. If several processes are executed in parallel. their results can depenJ on the unpredictable order in which actions from different processes aro executej. For exaaple the tvo siaple processes below can interact in six different ways to produce four different values for y proccas I: x:?l process 2: x:'2 y:=x.l y:=5?x Such complexity greatly incr?aaes t?c probability that the progr??er will makc niatakes. f.vcn worse, the ristacs ray not be detected during program testing. since the particular intersetiona in which the crrors arc visible esy not occur. It is inportant to structure parallel programs in a way which elininates son of this con.p'?caity, and to verify their correetness with proofs as well as by pro:ran testing. A number of methods have been used in proofs for parallel prograns. The most cor?on is reliance on infernal arguments -- a ria&y bus?ness `given the complexity of parallel prograr.. int,sractions. "ore fornal approaches have included application of Scott's mathenatical serantics (Cadiou and Levy (Ca73]), Lipton's reduction nethod'(Li74b]. and Rosen's Chureb-Rosser approach (Ro74]. The work which is ;ort directly relatol to this thesis is based on Floyd's inductive assertion nethod (Fl671 for sequential programs. In this approach assertions ate attached to the arcs of a flowehart, and a verification condition is developed which guarantees that whenever control follows an arc the corresponding assertion is true. This verification condition for sequential progra:s is fairly simple, but for parallel prtgr??s it can be quite co--Hplex. Asheroft and 4anna [As7l] express a parallel progran. as a nondetersin- istic sequential protean. This gives a sinplc verification condition. but the nunbee or assertions is an exponential function of the nunber of progran. statements. In [As73]. Ashcroft uses a similar technique, but argues that in practice the nunber of distinct assertions will not be too large. Lauer [La731 and \.`ewton (\.`e74) attach assertions to AXtO>ATlC PR(nF T?CIL\lqUES FOR PARALLEL PROGaA?'iS Susan Speer Owicli Ph.r). Cornell University 1975 This thesis presents an axionatic method for proving certain correctness properties of parallel programs. Axioms and inference rules for partial correctneas are given for two parallel program?ing languages: the General Parallel Language and t?e Restricted Parallel Lancuage. The General lan?uage is flexible enough to represeit most standard s)?chronizers (e.g.. senap?ores. cvcnts), so that programs using these s)?chroniters nay be verified using the GPL dcductlvc syatem. ilowever, proofs for GPL programs are in gcner.'l quite complex. The Restricted language reduces this complexity by requiring shared var?ables to be protected by critical sections. so that only one process at a time has access to then. This discipline does not significantly reduce the power of the language. and it greatly simplifies the process of program verification. Although the axioms and inference rules are primarily intended for proofs of partial correctness. there are a number of other Important properties of parallel prograns. We give some practical techniques which use Information obtained from a partial correetness proof to derive other correetnesa properties, including program termination, mutual exclusion. and freedom from deadlock. A number of e.?amples of such proofs are given. Finally. the axioms and Inference rules are shown to be consistent and complete (in a special sense) with respect to an interpretive model of parallel execution. Thus the deductive system gives an accurate description of program execution and is powerful enough to yield a proof of any true partial correctness foraula. s 1.2.?tlineoftheThesis. Chapter 2 is a review of hoare's axioms and inference rules for a sequcitial proeranming language (SL). There are no new results here, but many ot the corcepta needed for parallel prQ?rsms arc introduced at this time. In particular, an interpretive model for sequcntial execution is developed which is later exterjed to provide for parallel coa?utations. In Chapter 3 we move on to discuss parallel programs. The language presented here is called the general parallel language (GPL) because it is powerful esough to represent most of the primitive operations su?gested for syncronizing parallel processes (e.g., events, Oij?stra's seraphores). The deductive system and the model from Chapter 2 are exterded t3 include parallel operations. In Chapter 4 we consider a parallel programming language and deductive system suggested ty Ijoare. This restricted parallel language (flPL) is r?re hichly structurcd than the one given in Chapter 3, and this greatly simplifics progra? proofs. In fact, the size of the pro?fs again becomes linear in the size of the program. as it is for se?jential programs. Once again the interpretive model defined in Chapter 2 can be extended to cover the new language. Chapter S discusses methods for proving other properties besides partia cerreetness. Using both the deductive s"stcm and the interpre- tive model of program exec?tion it is possible to derive easilv-verified sufficient conditions fzr guaranteeing mutual exclusion, termination, and safety from bloc?ing. Chapter 6 considers the relationship bet'?een t:?? deduetive and interpretive semantics presented in earlier chapters. The two nethods are shown to be consistent for all' three lsngua:es, and the deductive system for RPL is sho?? to be cor?lete with respect to the interpreter. Finally. Chapter 7 sumrari:es our results and 5u???5t5 extensions and areas for future work. control Points in the flowchart of each parallel process. This nakcs the number of assertions lincar in the size of the pro?ram. Unfortunately the verification condition becomes more complicatej, hecat?se it is necessary to check that the statements in one process do not invalidate the assertions in another. This again introduces an exponential complexity Into the proof process, but in practice all but a few of the checks are trivial. All of the inductive assertion methods deal with flowcharts but they can be used as the basis of an axiomatic description of parallel programming languages. Instead of having assertions attached to points in a flowchart, they arc applied to program statements according to a set of axioms and inference rules. Working with language statements rather than flowcharts makes it easier to enforce restrictiona which ?ke programs intellectually manageable; it is even possible to co:pletely eliminate the exponential factor mentioned above. The axioms and inference rules provide a sound formal techniqum for proving partial correctness, but they are also intuitive enough to be used as the basis of reliable informal proofs. One of their main advantages is that they give guidance in structuring programs in a way that makes them easy to understand as well as to prove correct Although the deductive system describcd above is designed for pro?ing partial correctness, it can also be used to demonstrate other important properties of parallel programs. For example, mutual exclusion, the property that two or more proceasca cannot execute certain statemanta at the sane time, can be proved using axiomatic techniq?wa and certain theorems about program execution. Similarly. we can find 6, practical, sufficient conditions, in terms of the axiona, for showing that all processes cannot becore blocked (deadlocked). These results. combined with `lanna's work, make it possible to prove program termination in many cases. There are two questions which naturally occur in considering an axiomatic semantics for a prograrming language. The first is: do the axioms and inference rules correctly describe the results of executing a program? The second: are they powerful enough to make it possible to prove all true atatemcnts about a progrLa? A partial answer can be obtained by defining an interpretive model of program execution and then asking the questions with respect to that model, The first then becomes do the axioms and inference rules correctly describe the results of executing a program under our model;? If they do, the deductive syster. is said to be consistent with the model, It has been proved that bare's sequential deductive system is consistent with several models of program execution (Cook [Co7S], bare and Lauer (1l074b]) The second question becomes: is th. deductive system powerful enough to prove everything which is true about program execu- tion in this model? If so, it is said to be complete with respect to the model, Cook [Co7S] has recently proved that the sequential axioms and inference rules are complete in a restricted sense which will be discussed later, In this thesis, we will show that the axio:s given for parallel processing are consistent and complete in Cook's sonso for one model of parallel execution, cal?ulus. For eaafl.p'.e the forula (xy<' =:?(x.y)I2 (x"??) expresses the fact that if x < y ?ten the statement ::=(x?y)/2 begins. x < y < z will be true wher. (and if) the statenert finishes. Table 2.1 gives two axion. sehemas (Al ad A2) and four inference rules (AO, A3-AS) for sequential proerans. The notation pp p n for inference rules means that P can be proved by proving each of the P. and then applying the inference rule. Al-AS correspond to the five kinds of progran statements. ?ule AO requires some additional cor.?ent. The notation P ? Q means that it is possible to prove q using P as an assumption. The deductive syatea to be used in proving Q fro:n P is not g?ven: it could be any systen. ?hich is valid for the data types and opcrations used in the pro?rar?.T.ing language. For exanpie if the program?ing language contails natural numbers and the operations and the deductive systea could be based on Peano's axioms. Figure 2.1 gives an example of a partial correctncss proof. The proerso po?er cooputes z-x ir y > 0 (x and y arc integers). The partial correctnesa condition is (y>O) po?er Lines 1-2 describe the statement labelled init 1, lines 3-4 describe init 2, and lines 6-10 describe the loop. Finally. the effect of the three statements together is &iven in line 11. 10 AO conscquc?ce S(0')PP'0'?Q (PI 5 Al assir,nmcnt (pX) x:?L (PI ?hcrc prX rcprescnts he rcsult of suostitutin? c for each free occurrence of x in P c.g. if P is (a>OV b-l) Pa.? is (s'b>O v b-l) A2 null A3 composition A4 alternation AS itoration (PI)5(P2),(P2)?2??3???n?5n??n?l? (P 1 bc?in 5 5 cnd (P 1 I n --H n.1 AEl?i(q)(P.??B)?52fQ) (P) if B thcn else ?2 (Q) (P A a) s1 (P) tP: ??jle II do A ,II Table 2.1 A?ioms and lnfcrencc flules for sequential Pro:rars. Cit1PTE? 2 sEQu?\.T1AL PROGRk'tS Wc begin our studv of parallel programs by describing a simple sequential language which will be the basis of our two parallel languages. Th? sequential language is a fragment of Algol. ?or which Noare has given a set of axioms and inference rules, ?c definc a si:ple interpreter for this language and sletch a proof that It Is COfl5i5tCflt wi',h Hoare's deductive system. Chapters 3 and 4 will extend the language to include constructs for parallel programming. ?.a.Theae?uefltialProerammin?Lanrua?e(SL). The programming language SL contains five statements: 1. assiancent o+- x:-E where x is a variable and E Is an expression 2. null 3, compound -o+ be?in 5 `S end n 4. alternation ,- if 0 then else 5. iteratIon -? while 0 do where a is a Boolean expression and the 5. are statements. ?ote that there are no declaration statements; it is assumed that all variables are globally defined, This simplifies the axioms and the model of progr?i execution, but declarations could be included without changIng any of the results, Sea Lauer (La7l] and Cool: ?o7S) for the treataent of variable declarations. ?/ .%?.. ?e also choose not to spccify the s)fltax of expressions. ?ost of the time wC will USC the atandard Al?ol syntax for integer and logical expressions. but the techniques apply equally well to other data t)pes and operations. At times it will be user?l to spC5l of the relation between a stateoent and the atatemCnts it contains. Let s be an SL statement. ____________________ 2.1.uetinttjon. The primarycorn?onents of s are 1) none if s is an assignaent or null 2) S1.S2s if s is bc?in S o+Sn end __ 1--H 2 3) ?l' ?2 if s is if 8 then else S 4) s1 if S is while 8 do ?l The propercon?onents of s are the primary components of S and their proper components. The components of s are S itself and its proper components. 2.2.Thefleducti?eSc?antics. Hoare (IIo69] has dcveloped axioms and inference rules for proving the partial correctneas of sequential programs. He uses the foraula (P) S (Q) to represent the partial correctnesa of the program s with respect to assertions P and Q . This fleans that if P is true of the program variables before executing s and if s terminates, Q will be true of the program variables after execution of 5 is complete. P and Q must be formulas of the first-order predicate 13 fy>o) powcr: be?in :-1; tcmp:?x; A :.xY?tCff.P) loop: w!'ile tcmp>O ?o v-t (ter..p>o A z-x' flP) ?ult: bc?in z:-?c.z; tcmp:-tcnp-i cnd (tcr..p>o A z?xX?tCr"P) (tcn.p>O A z?xY?tCn.P A end ?i:urc 2.2. An Infornal Partial Correctncss Proof. 14 Civen peCS') and post(5') for each coponent 5' of 5 it is posssble to recenstflct a proof of (PI, 5 (Q) if pre(5') and post(5') s.?tisfy certain requirements. 2.2.Definition: Let pre and post be functions which rap ce.-?onents of 5 to assertions. Then pre and post are assertionfunctions for (p) 5 (q) iff they obey the following restrictions for each coaponent 5' of 5 1) P ? pre(S) and post(s) ? Q 2) if 5' is x:"E , prc(5') ? poat(s,)?X 3) if 5' is null, pre(5') ? post(5') 4) if 5' is bepin 5 5 end a) pre(5') ? pre(51) and P0St(Sn) ? post(5') b) P0St(5j) ? prc(5i?l? i-In?l 5) if 5' is if B then 5 else a) pre(5') A B ? pre(51) and pre(5') A 18 ? pre(52) b) post??l? ? post(5') and post(S2) ? post(S') 6) if 5' is while ? do a) pre(5') A 8 ? pre(51) b) post(s1) ? pre(5') c) preCs') A `8 ? poat(5') A proof of (P) 5 (Q) and a p?ir of assertion functions for (P) 5 (Q) are very closely related. Civen eit?er one, the other can be derived as shown in the next two theorera. In ieneral, we will first give a partial correctness proof, then derive assertion fur.ctions fro? it. 11 po?er: be?in initl: :::?l; init2: tc¶.p:.)r; loop: while ter.p>O ?o ault: bc?in up:: ::?x.::; downteop: ter..p:.tcmp?l end end 1. fy>0 A 1-1) :::-l (y>o A :?l) Al 2. (y?o) z:-l (y>o A -1) 1, AO, using y>O ? (v?O A I-I) 3. (y>o A ::?l A y?y) temp:-y (y?O A --1 A tenp?y) Al 4. (y>o A -1) tcrnp:-y (tc?p>O A ??xY?tCrflP) 3, AO S. fte?.p-l>O A ?*?"?Y?(tC???l)) z:-x.z (tci.p-l>O A z?x? (tcrnp-l)1 Al 6. (te?p>o A ???Y?temp A tcw.p>o) ::-x.:: (tcn.p-l>O A ???Y?Ct?n.??l)? S, AO 7. (te?.p?l>O A ??Y?(tC0??l)) tcn.p:-tcr?p-l (te?p>O A ???Y?tCtfl?) Al 8. (t?opo A ,-??Y?te?p A tcn.p>O) nult: be:in ?:-x,,z; tcmp:-tcmp-l end ?temp>O A ::`xY?tC1flP) 6, 7. A3 9. _____ tcnp>O do mult fteop>O A ??Y?tC??) loop: whilc (temp>o A ::??X?tcmp A `(te?p>O)) (te?p>o A ???Y?t???) loop 10. 11. (y>o) power 8, A? ?, AO 2, 4 10, A3 ?iguro 2.1. A Fornal Partial Correctnesa Proof. ffi.?. 12 c?urse this is a very tedious proof of a si?ple result -o+ much like an algebraic proof that (a'b)(a?b) a 2ab b when every use of the cor.?utative and distributive laws is presented. Figure 2.2 contains a more informal version of the sare proof -- assertions enclosed in braces () are interspersed with the progras, while some of the proof steps arc combined or omitted. `.!oat of our proofs will be presented in this style. hhen proving progrars correct in a practical manner, we use the formal methods only in the difficult parts and use less formal techniques on the simple parts. The most difficult part of sequential programs is iterative loops. and it is usually worthwhile to carefully apply inference rule AS to each while statement. On the other hand, assignment statements and be?in ... end blocks are relatively simple and can often be treated informally. In Figure 2.2 the assertion P (temp>O A =?y?temp? appears iuat before atate9.ent mult. This corresponds to the fact that P `mast hold whenever mult is ready to be executed in a corputation which atarta with y 5 0 . P can be called a pre-candi-ion of mult, and Q (temp>O A ?????t??P) is a post-condition. A proof of (P) 5 gives at least one pre- and post-condit?on for each component of 5 For example, line 3 in the proof of (y>O) power (?.??) gives the pre- and post-conditions for mult cited above. Lines 9 and 10 give two post-conditions for loop, namely (teapsO A ??y?temp A ,(temp>O)) and At times it will be useful to single out a particular pre. (or post-) condition of a statement 5 and call it pre(S) (or post(S)). 17 section usca an operational approach, in which the effect of a program is ?eacri?cd by gi;iflg an interpreter for the prograT.a.ing lancuage. This interprotive eodcl is consistcnt with the dcducti?'e systcm. It will be used extensively in Chapter 5 whcn Jiscussing nutual cxclusion and blocking, which cannot be cxpreaaeJ directly in teres of partial correctness. The interpreter for an SL progran consists of a set of states 3rd a state-to-state transition function. A program state has two coaponents -- a control, which gives the next instruction to be exccuted, and a variable state which gives the current value of each vari-ble. 2.5.Definition A proeramstate for a program S ia an ordered pair. a"(c,v) in which 1) the variahestate v is a function from variable n&trea of S to valucs. 2) the controlstate c is a tree in which every node is labelled with a atateflent fro? 5 in such a way that if 1 is a corporen of , and ?i and both appear in c , ?l is a descendant of 5, . (flere each node is considered a descen- dant of itself.) The variable state v is a function defined on all program variables, although the value returned for an uninitialied variable `s not specified. The notation L(si will be used for the value of expression E in state s"(c,v) . Thus. if v assigns 0 to a 6, 18 For an assertion P we say P is trje in a if P[s]?true The control state for a sequential program is a de:?nerate tree in which each no?e has zero or one sons. The single leaf is t?e next statenent to be executed. n order to sinplify notat?on we will assign a unique label to each stateTent and use the staterent and its label interchangeably. Fi?ure 2.3 conta?na exarples of states for the program power of Figure 2.1. Note that the derin?tioi. of control state guarantees that no staterrent appears more than once in the tree For 5 is a conponent of itself, and i- 5 appears at nodcs m and n m must be a descendant of n and vice versa. So ti?n The execution of a atateent can affect both cenponents 0' the program state. The control is e?dified by rep?acing a leaf by a (possibly eapty) tree. 2.6?e'.inition: If t and t' are trees, and n a leaf in t eplace(t,n,t') is the tree obtained by replacing n by t, in t Examole: t - t' - e g f dffib replace(t,d,t?) ffib fe replace(t,c,r) - a d?Thb where r is the eapty tree. IS The assertion functions are useful in proving the consistency of the deductive syste? and in discusaing vario?s prooortics of parallel programs in Chapter 5. The key point is that pre(S?) must hold whenever 5 is ready to execute and post(S?) must hold whenever S. is finished. 2.3.Theorem: If pre and post are assertion functions for (P) 5 it is possible to prove (pre(S?)) 5 (post(S')) for each component 5' of 5 Proof: By induction on the structure of 5' . Two cases will be :iven; the rest are similar. Caso 1: 5' is x:-E 1. (post(s,)X?) 5' fpost(S')) Al 2. (pre(S')) 5' (post(S')) 1 AO and requirement 2 for pro and post Caao 2: 5' is wh:le B do 1. (pre(s1)) Sj (post(s1)) induction 2. (pro(S')AB) ?l (pre(5')) 1, AO. requi--H.ements 6a, 6b 3. (preCs')) 5' (pre(5') AiB) 2, AS -A. (pre(S')) 5' (poat(5')) 3. AO, and requirement 6c 2.4Theores.: 1 there is a proof of (P) 5 (Q) there are assertion functions pre and post for (I,) 5 (Q) Proof: Pro and post can be obtained from the proof; they will be defined in such a way that (preCs')) 5' (post(5')) is a line in the 16 proof. for tach component 5' of 5 . Since the proof may contain eore than one line which refers to 5' we a?st specif,v which line is chosen to give prc(S') and poat(S') e elirjnate all lines w?ich do not contribute to the proof of (P) 5 (Q) (for example. line 1 in the proof of (x?) ?:?(x.y)I2 (xO) z:=(x.y)/2 (:>O) Al 2. (a<(x.y)/2v) z:-(x.y)?2 (x > ? o ? CM `a ? g E o+ a a c 0 0 0 in oC? 6/ %?o+?. 20 Tr.e vart?ble ?tatc can be noJif??d by an assignment state:nent. The nc? variable state will be the sane as thc old except at the variable ?hich recei?cd a 2.7.flcfinition: If v is a variable state function and E is an expression, v is a new variable state f?nction defined by x[v] - x(v] if x 6 a - E(v] if x a The effect of each type of statement is defined by the state transition function `next". An assignnent statement chanres both the control and the variable state; all othera change only the control. Note that if S is a compound statement (be?in . end, if or while), nextCs.S) describes the effect of startin' S in state 5 rather than the effect of a coeplete execution of S 2.a.riefinition. The state transition function next: (program states) X(stateoents) (program states) is given by next(Cc,v).S) - Cc',v') if S is a leaf in c - undefined otherwise v - v if S is x:-E - v otherwise where 25 Proof: The pro3 uses ind'?ction on the length of a If a is e=pty 1) is satisfied beca?se P is true for and P ? prc?S) 2) does not app?'... tor a a'T preC?) is true ater a by in?uetion. Proving t?at `,) ard 2) arc satisficj for a' is a straightforward but teJio?s applic3tion a t?e definition or assertion functions. The details are given in CI:apter 6. .10.L.,rojjar?. If ?`P? 5 can be proved, it is true for the interpreter. Proof: By Thcortr.. 2.4. there are assertion functions pre and post for IP) 5 (Q) Ne? suppose a executes 5 from state 5o with true. Thcn by the last theorem, post(S)(valuo(50.a)) true and qr?value(s0.a)) true since post(S) ? Q . So (P) 5 (?) is true for the interpreter. This inishes our review of sequential programs. In the next c??pter the axioza and the mo?el are extended to parallel programs. CIlA?TLP 3 PA??LLL P:?oG:?'ts In tha ch?pt?r we introuce par?1lel prograns by exte?Aing the l?n?ual:e of Chapter 2. Two ncw st.dtt?ents Will be added co?e?ir. cound to in?tiate prallel exccj'tion, and a synchroniat?ofl state=ent calleJ a?ait to coorJjnatu proceast's executir.g in parallel. The await atateeent is very flexible in fact it ia too ?eneral to be ispl?r.ented in an efficient wa:/. It is included here because it can be used to represcnt ¶.any standard synchronizing prir.?t?ves, such 35 es'cnta and s??aphorea. Thus, the proof techniques for GPL can be applied to prograns which use these s>mchronlzers. Thc lanruage in this ch?pter is relatively priritive ard provides only li.:ited facilities for strjcturin,, the interactions of processes using shared variables, ?e will see that the axie.?s for the parallel and synchroni?ation st.?te.ments are easy to understand; they state quite easily when we can knew that parallel processes don?t "interfere' With each other Put proofs usia',,' the,, Will be difficult because of the esporential nurber of chec'?s that ray be necessary to satisfy this noninterference criterion. In C:?apter 4' we present another lanuage in which the usc of shared variables is closely rezulated; this nales proofs of prograr'. correctacis r,jch siapler. `lowever, no suCn larguage is yet in usc (see Irinch flansen [Br74)) so the results in this chapter are nore rea?ily applicable to prograns written in the lanuages which are currently available. 26 -.?L.Lcr11.1t1o.?: If a is a computation for S and S' is a c??poneflt of S a finishes S' iff 1) s' is an assicnnent or null stateaent, and S. is the last statenent in a , or 2) s is while B do S1 S is the last stateaent in a , and 3 is false after a , or 3) S is berin S ;Sn e?d and a finishes S , or ) S' is if 3 then S1?else S2 and a finishes S1 or Esan-ole: Fro? Fifure 2.3f, a - (power, initi, init2, loop, body, up:, downterp) finishes downtemp and body. 2.12.Definition; a executes S iff a is a computation for S which finishes S cxa--H?le: Fror. Figure 2,3i, a - (power, initi, init2, loop. body, up:. downte?p. loop) executes power. Note that for a ?iven initial state 5o there is at most one compu- tation which eAccutes S This is not true for parallel programs. If s contains an infinite loop. no computation executes S 2.13.Definition: exicute(a,S) --H value(s,a) if S is ready to execute in a snd a is a computation which executes S from state a If s is not ready to execute in a , or no such a exists. execu:e(s.S) is ui,defined. This completes the description of the interpreter for sequential Pro:ra;as. In Chapter 3 it will be extended to include parallel programs. y 24 2.4.Conr,:ste?cvert'.:cIJeJL'ct.vevarer.antheInterreter. Sections 2.2 and 2.3 specify tre serantics of the language SL in two diff?r?nt ways. In this icetiun, we state a theorem to the effect thit the two n?thods are consiste.?t. To keep the reader froo gettin,, bo,ged dot? in details, we only sketch the proof here, delaying a co?..plete presentation until Chapter 6. Ilopefully, both nethods corrcspond well enough with the reader's intuitive idea of program execution that he is willing to believe they are not contradictory. In order to show that the deductive syste.' and the interpretive ?odel are consistent, we must sho? that (P) s ?Q? can only be proved when it Is true for the interpreter. 2.14.I)e?initinn: (P) s (Q) is truefortheinteflreter iff an7 coaputation 0 which executes 5 from state 5o with P(s0] - true has Q(value(50.e)i true. order to show that a proof of (P) 5 (Q) irplies that (P) 5 (Q) is true in the model, we first derive a stronger result using assertion functions. 2.15.Thcorcm: If pre and post are assertion functions for (P) 5 (Q) 5' is a component of 5 , and a is a computation for 5 from a state a0 with P[a0] true, then 1) if 5' is ready to execute after a , pre(S') is true after a 2) if a finishes 5' . post(5') is true after a 29 P(sen.): s?ait sen)O then scn.:=sern-l ?`(se:i.): await true th?n sen:?stn?1 Lipton (Li7?a] describes a n?rnbcr or ecnerali-ations or semathores; 311 can be ir?'e:'ented usine await statenents. l? [Di6Sb). Di?kstra :ives a s1i?htly different definition of the seraphora operations. P?(sem): se?:=sern-l if sercO then the process is suspcnded on 3 ojeue associated with sem. V?(sec): sen:?se=.l if scnO sem:?aeo-l otherwise the process is suspended until sensO V(aem): sem:?aen?l The P and V operations are Indivisible. They can be represented by synchronization statements as follows. 33 si 0 ? u v: v: v:; 00 34 it is not. T?c soutien iCt proirars so t.?at i:?? ass?.ption of indivisihility is reaionable one. For exarple, if exeiutin two Jctions sir.ultaneo?sly is tic ia.?e as exicutin," one and ten tIe otler, it is res?onable to treat then. as indivisible. This certainly is the case if the actions do not .?a'.'e an? variables in coron. If they do, sone care is rc,'ulred. 3.S.!)efinitinn: TIe variable x is shared in cc".er-. S,//. ?/?S? coend if it is referenc?d in t'?o or T.?ore of the S. and chin:ed __________ I appears on the left aide of an assigninent) in at least one of thc?. It is refer?nces to shared vari?ilcs `hich cause problens whcn actions are treatea as in?s?ia?ble. Lut for actions `hieb r?ke at rest one reference to a shared variable t"e assuoption of indivisibi it'1 is reasonable. If two such actions are executed sicultaneously. one of then' nust Saki the first access to the shared variable. The e?feet in parallel will be the sane as if this action was executed first and followed by the other action. In the interpreter, three kinds of actions are assuted to be indivisible: I) an assignment atatirent 2) evaluating the ?oulcan expression in an if or while a) synchrenitation statement. 3 is no proble¶., since a s1nchroni?ation statement ii interded to be indivisible in parallel esecution. I and 2 are 3ustified if each aaai,'r,n.ent and each if or w\Nil' condition contains at ?ost one reterence 31 parallel proeran. unlike a sequential pro?ram. can lead to a control tree with more than one leaf. The function `next must be extended to handle parallel and swnd?roni?ation statements. next(s,S) ia defined for all statements S which are ready to execute in a 3.2.Defin??u,,. A statetent S ia current in the proeram state s-(c,v) iff S ia a leaf in c 3.3Definition: S is readvtoexecute in state a?(c.v) iff S is c?rrent ir. a and if S is await B then S1 B[sj?truo. Xote that for sequential prograns thia reduces to the previous definition of "ready to execute'. 3.4.Definition: The state transition function next: (program statea)X(statementa) (progran states) is given by. next(Cc.v),S) undefined if s is not ready to execute in (c,v) - execute(Cc',v).S1) if S is await B then S1 where replace(c.S.S1) (see Definition 2.13) --H (c?.'.) if S is coberin S1//.. coend, where c' is the tree obtained by deleting S in c and adding ?? as sons of S'a father, if any. and otherwise as roots of unconnected trees. - Cc v') of Definition 2.8 if S is asai?nment, null, sequence, if. or while. 32 The de?nition naxt((c.v). aait B thtr. S1) - execute((c v)`5l? retle?ts thc assur.ption that executing?an a?ait ataterent is an indivisiblc op?ration. Figura 3.1 contains examples of t?e application of next. Note that in 3.lb the control state is actually a forest rather than a tree. In this model parallel execution ia si:,.ulated by nondeterainism. lnstaad of executing the processea in cobesin ? //Sn coend simultaneously it perforra one action at a time. choosing nondeter ministically which process to work on ne?t. This reans that in the program newx: be?in x:'O cohe?in A: x:-x?l /1 B: x:-x-l coerd end either A or ti is cxecuted f?rst they cannot overlap. TIja use of nondetereiniam is standard in models of parallel execution, but it requires some justification. For example. the program above, executed by the interpreter. must finish with x"O . A true parallel imple- mentation might finiah with x-l if the actions took place as follows: 1. A evaluatea x.l 2. ? evaluatea x-l 3. a stores -l in x 4. A stores 1 in x The discrepancy arises from the fact that the assignment x:-x.l is treated as an indivisible operation by the interpreter, when in fact AO cor.scq?cr.?e 37 5. (??`, ? 0 ? 0 ip;. s (Q) Al assi?flr..cflt (P?) .?:--L jP) A r:jll A3 con.?osition A4 a1tcri.?t1On AS iteratiom A6 s>?c1.ror.iation A? parallel t'P1)S1(P2' .(P2)?2(?3?P?)S?(P??1) b('tin S nd (PA B) S1 (Q (PA `? S2 (Oj (P) i 13 thcn S1 clsc S2 (Q) `.P A 3) S `?.` (P) hi 3 d? 5 (P A `13) A 3) 5 (P) ??ait B t?cr. S (Q) (P ) S (1 ) (P ) 5 (Q ) In n n (P1 A.. A P ) ?c?'n ?l??. /AS? cocnJ (Q1 A.. A provided (P1) ?l (Q1).. (P?) 5? (?) ?re intcrr%rence- free Tab1e 3.1. Axic,ms and Interence ?ulea for CPL. ocs nt r.?J?fy any s?arcJ vj?i.bi??. T,is ra,:es t?e proccsscs cots- p'?tcly ir'jc??ndc.?t. it ir, ,oo ?rc.s,,' ? rcn??'rctsent. A ore serul r'?triction i? ti?:it t.;C ..ts?crti'r: ic in prr'vifl; S (1.? arc I I I in':?rsant as stat?oonts fror. other pro?esses are execuzt:? For tic ns?ertion ?.x?.' I.'. 5,- re.-'.-a?ns true throughout t.'Ie eseC-.it?on or x:?x'l in 5 ,r.c ,nvarlance or an assertion P o'cr a sratcr..ent S `s. e.:snples: Figure 3.2 contains a p?rtia1 correctness proof for a very simple pro,"rao. The fact that (x--n,'x?2) 51 (x"lVx"3) and (x?Ovx-I) 52 (x=2,'x"3) are interference-free can be verified by four tests. 1. (preCsl)Apre(S2)) 52 (pre(S1)? i.e., ((x-OVx.2)A(s-oVx?l)? 52 (x?GVx-2) which can be derived from (x-O) x:?x.2 (x"2) usin? A6 and AO. 2. (post(51)Apre(52)) 52 (post(5l)) `a. (pre(52)AproCSl)) 51 (pre(S2)l 4. (post(52)Apre(51)) 51 (post(52)) Note that pro(s) ? (pre(Sl)ApreCS2)) and (post(5l)Apost(52)) F post(s) S: cobeeifl (??o ? N=2? S': ?ai true the, x:-?.1 (x-1 ?` x?3) `I ?x=O V x'1) S2: a??1t true then x:-x?2 ?`x?2 V x=3) 41 ?i??re 3 2. A Partial Correctn?s5 Proot of a P?ra11cl Progran. 42 c.\a?,S?e of sn??.r.f r.3rc rcaIis??c p-.oblcr., tt?siier t:?e rrn¶ra Fir.?p3s in I?ure .3. a essest4aly tar. as a prt?ra whi,c co,rt?tr?s.s as pr???? I.y kC5e.s t?o7?) C.ivcn an array x of interers. it r.?nJs t;.?irat rositive cosporent x(J if t?ere is one jair ?`o paraliul procc?t'S to cntc'. t?? odd as e'?en suoscripted arraa,' cicrerts. [i?ure 3.4 ,?:ca the aasert?uss used in an axicratic prouf. It ?s not hard to see t?:at the:? eor.sti.tJte a pr?af r-rov?dcd that the assertions for .addsearz. and r.?'ensearch are interference-free. To verifa thiS We oust show that for each statenent T in Evenseare". and each assirn:nent T' in Odr.eareh (preCT)Aprt(T?)) To+ ipreCT)) (poat(T).?pre(T')) T' (post(T)) cThe argurent that Lvenseareh does not interfere with Oddseareh is aysj??ctric.) The on?y part of th assertions in evensearch wbich could be ehanged by an assignoent in ?Jdseare:.' is > ?.in(o?dtop.e':entop) which aight be ehaneed when oddyca sets oddtop:?j . So we r?st ehee? -. ein(oddtep,eventtp) t. pre(oddyes)) oddtep:-j > e.in(oJdtop,e?entop) 43 Findpos: bc?ii, integer M x!L:?) initiali=e: i:?2; i.?1 eventop:?oJJtop:??.1; search: cobe?in evensearch: whi!c iO t?cn cvcn?'es: eventop:-i else evenno: i:-i.2 od?scarch: ?hile ?0 t!.en (Is A x(i??O) c':cfl:'cs: evcr.top:'I (rs) e!?e (LS !. j,.,tn(oddtop,e'iantc'r,?) (os) Oddscarel?: -.4iIa j0 then (r)S A )<`A?l A x!j]>o) oddycs: oddtop:-j else (05 A jrnin(oddtop,eventop)) coend (o A 5 A i'-n.n(o?.dtop?cvcntop) A j>?jn(oddtop,ever.top)) k:-min(oddtop.eventop) A Vi (0< i0)) os - (oddtap<:4?l A ?k((.': odd A o0)) (05) (05) Figure 3.4. Partial Correatnoss Proo?. of Find?os. Since 45 preCodd?'es) (05 A j < ?dtop A x[jl > > < oddtop) the test is satisfied. 3.?.Can?istctc?'ofI';?e!uctives'???.-`heI In Secion 2,4 we discusscj consistcncy for the two dcfinitions of the se?antics of SL. Here we deri?'c sluilar results for CPL. Once sesin a foreal proof of the rain theorcr is delayed until Chspter 6. 3.15.Thearer: If pre and post are assertion functions for (P) 5 5 is 3 corponent of 5 and a is a computation for 5 from 5o with P[s0]=true then I) if 5' is curren' after a preCS') is true after a 2) if a finishes 5' post(5') is true after a Prof: By induction on the length of a . The details arc given in Chapter 6. I' a is cepty, 5 is the only leaf and pro(s) is true after a sirce P ? pre(s) . For CL m'T if 5' is current after a it either btc?.e currcnt when T was executed or was already current after a' . in the first case, pre(T) is true after a' by the injjction h,'?othcsis, and starting T makes pre(5') true lust as in a sequential program. In the second case, T and 5' arc state.?cnts fr?? different parallel processes. By induction, pre(s') is true after a' and pre(S') remains true as T is executed because of thc interference?free property. 3.Ib.ton': (Cen?i?tcrn?y for ?L) If `:P'? s :0) can he poved It Ia true for the int?rpretcr. Proof: Since ?P 5 iQ? can bt noved there arc assertion runctions pr and po?t for (Pi' 5 (q) (Teurer.. 3.14). No',,' surplie a executes :1 tron ???? ?6 with P[s0)tr?e Then bv, the last theore.., post(S)(value(s0.?)]?true , an':' .?[value(sc.?)].true ain::e post(S)-? Q So (P) 5 (q) is true for the interpreter. As a thin e?a?9le of a ?,?L prt?f, `,,e considtr a standard proble? fron' the litvrature of parallcl prozrar.r.in,,. A producer process generates a stre:,m of vaucs for a ccnsur..er process. Since the produc- tiOfl and consunption of values proceeds at a variable but reurhly equal pace, it it profitable to inter,rose a buffer bet-?een thc two processes, hut since storage is l?r.ited the buffer can onlI' contain I,' val?cs. Fi?uro 3.5 shea's on? toiutien to this probe.. lore the variable o+`in? counts the n??ber of va'?uos a'n?ch have beeadded to tIC buffer, and buffcr[in and ;j is the next erpts' b.?ffer position (if Lhcre is one). The variable "out" counts the n?r.'aer cf valees which have boon rc.'.'.oved, and buffer(e.'it rod.'?] is the ne?t full position. There arc (:r'-out) values in the buffer. The a'?.?it staten'ent in the producer prevents a ??:-? roe being added when t:?erc is no availabl space, while the' ?`...`.i. in the consunor do's/a reroval until there is a value in the buffer to be renoved. Figure 3.6 ccntains a prone fl ah?ch eo-.putes l['?) - 1 ... `I usine this pneducen-consuo.er sencre. Fi:une 3.7a-c sives assertion functions for (`.!?O'i f:l `E[?).f(g(A(&'))) fgl: ?c?in ln:--Hout:?O; i:--Hj :?1; (i A i?in?I-1 A j?ou??1?i) ccb??in A i?in.1?i) pro?u??r (I) A j-out.1?1) cons??r (i A ?(k]?f(g(A[k))). 1O t?en; remove: this value : buffcr(out mod N]; rarkout: out:?out.l; Pleure 3.5. Prod?cer and Consuser Sharine a ?ounded Buffcr. f?1: hc?in c?nent bu?r?r[O:N-l) is to shared b??=cr in n?n..ber o e1?'rcnts added to `)ur?er out nur.I,?r of e1e.?ents rer.??cd ??on bucrc.r 1n?out = n?r..ber of elenents in burfer; in:=o?t:=O; 1=5:1 eobe?in producer: bile iO then; reeve: y:=bufcer[out rod N]; markout: out:-out.l; end coend end Figure 3.6. Computation of ?(ki-f(g(A[k])). !O th?n; (i A IC A j?out+l A jO) remove: y:?buffcr[out mod \.`]; (1 A ?C A j?out.1 A j 0). The assignnents in the producer leave these three cor-ponents unchanged: I is also an in?arisnt in the producer; the variables in the second conponent are not affected; and the only assignment that changes (in-out) is markin: in:=in'l which leaves (in-out > 0) true. Sinilar reasoning shows that assertions in the producer are invariant over statements in the consuser, so the interference-free criterion is satisfied. ?.a. j'uxilisrv ?arianies. In many cases the axior-s and inference rules AO-A7 are not strong enough to prove a partial correctness forrula which is true, Figure 3.8 is an exs:nple of a program where the deductive systen. fails. The formula (x"O) add! (x-2) is true, but it can't be proved using AO-A7. To see this, consider post(sdda). If the program starts with x"O , it can finish adds with x-l or x"2 depending on whether or not addb has been executed. So the strorgest possible assertion for post (adds) is (xl V x?2) . The asme Is true for post(addb). Since (post(adda) A post(addb)) ? post (add!) , the strongest possible assertion for post (add!) is (x-l V x?2) , in spite of the fact that after executing add!, a must have the value 2. ss add2: beein y:.O; z:?O; cobe?in (x?: A y-o) await true thembe?in x:?xt1; y:-l end (x??.1 A y.i) (x-)' A x-o) await true thenba?in x:-x+1; ::-1 end (x-y.1 A z-1) coerd (cx.?.1 A y-l) A (x-y.1 A z-1)) end Pigure 3.9 The Program add2. F - S6 were c V ()?l(tin',: ?:--H-F 2 irplacIng aw?it tr?e tin x:= 0:: . provide x:?E i?a?es at no?t one refcrcn?e to a snare variable (In tbis case, x does not have to be an elenent of AV,) ?. ?eplacing be??n S e?d by S We will write S-red?ce(S' ,S0) where S0 is the statenent eli=inated in goin, fron S' to S i.e. , in 1) S0 is the assignent, in 2) the await statenent, and in 3) the bein- ed. In our example, adel can be obtained fro. ac'd2 by repeated applications of the operations above. `.;??? that in order to reduce await true then l'e'in x:?x'l; y:?l end to a'?ait true then x:'x?l we nust first delete y:=l (operation 1), then t;?? berin - cd brse'?ets (operation 3). The a?flchronizati0n atatenent cannot te re--Haved because x:"x.l contains t?o references to a . It is safe to re?ove a synchroniration state.m,-.nt when rule 2 applies, because then the assignment statcnent can be treated as indivi?ible anr?ay. !;ow we give the inference rule which alle'?s us to conclude (x"O) addi fx'2) fron a proof of (x"O) add2 (x-2) ASAuxiliarvVariablec. If AV is an suasliary var?ab1e set for S S a reduction of S' with respect to AV, and P and q assertions which do not contai' free any variables fram AV, then (P',S'(0) (p) s S3 fx?o) addi: cobc?in (x-o v x-1) adda: await true then x:?x.1 (x-I V x-2) (x?O V x?1) a?d?: await true then x:-x?1 ?x-1 V x-2) cocr? (x-1 V x.2) Figure 3.8. The Progra? addi.- 54 \?ow consijer Figure 3.9 an c,panded ?`crsi3n of ad?l. T?e reader can verify tiat the ass?rtions in Figure 3.9 are irterference-free and yield a proof of (x--O) add2 (x=2 . The proof depends on the variables y and . Since ajj2 has the sar? effect on x as aAdl. we would like to be able to conclude fron this that (x-O) add `x.2) In order to do this we will decinC the concept of auxiliary variables and then ???? a new inference rule to allow th?ir use. The program add2 has ess?ntiallv the sane behavior as addi in spite of the fact that it contains statements and variables which do not appear in addl. This is because t?e additional variables. nd the statecenra usin then., do not affect the flow of control or the values assigned to x . \`ariables ?hich are used ii. this way in a progran. will be called auxiliaryvariables. The need for auxiliary variables in proofs of parallel programs has also been recognized by erinch hansen [8r73] and Lauer [La73]. 3.17.Detinition: Let AV be a set of variables which appear in 5 only in assignment statements x:?E where x c AV and any variables may be used in E Then AV is an auxiliary variable set for 5 3.18.lefinition: Let A" be an auxiliary variable set for 5 . 5 is a reduction of 5' with respect to AV iff 5 can be obtained fro? 5' by one of the following operations. fg2: be?in co=r.cnt buff?r(O:l:-l'j is the sharcd buffcr full nu?ber of full placca iu b?tfcr ?scmaphorc) e.?ty - numbcr of cmpty placcs in buffer (scmaph?rc). full:-O: empty:"N; i:--Hj:-l; cobe??n producer: whjlc j<'.I do be?jn x:.:(A(iI); PCcmpty); buffcr!i ?od N]:-x; V(full); i:.i?l; I, end consumer: while j0) fb2 (a(kj= f(g(A[k))).l0) fg2 (u[k)-f(3(A[5))). Ilabermann [11a72) presents this solution to the producer- 63 consuner problem and pro??ides an informal proof of its corrcctness. For the pr?or. be uses special functions which count the number of P and V operations on each semaphore; yhese play the same role as our auxiliary variables. 3.6.`??tualExclusion. It is often necessary to ensure that certain critical sections in separate processes cannot be executed at the s?me time. `test often this is because the critical sections nanipulate shared variables. and it is essential to prevent them from interfering with cach other. Ore of the standard ways of ensuring mutual exclusion is the use of a secaphore ?utex whose initial value is 1. Each process executes P(mutex) on entcring its critical section and?V(mutex) on leaving. Our techniques can be used to show that this discipline does indeed ensure autual exclusion as long as there are no other operations on the semaphore mutex. Figure 3.13 shows a group of cyclic processes containing critical sections. The statements in the critical and noncritical sections are not specified. but they do not operate on mutex. In Section 3.1 we suggested a representation of tho P and V operations as PCse?) --H await sem>0 then sem:-sem-l V(sem) - await true then sem:-sem.l Thus the code for implementing mutual exclusion in GPL is 64 bc?in mutex:1; cobegin Si /? ?/ Si: ?b?le true do be?in noncritical part; P(r.?tex); critical section i; V(mutex); noncritical part; end coend // Sn end mutox is not chan?ed in t?e critical and noncritical sections Fi:uro 3.13. Critical Sections with ??tual Exclusion. 61 ?g2?: be?t'n fu11:?U; e?pty:?N; i:-j:?i; PEull:-Vfuli:?Pcmpty:.?cn.pty:=o; (1 A Vfull.Pcn.pty A ?=Vfu?l.i.l A Vetnpty-Prull A j-\cmp?y.l??) cobe?tn (i A Vfull-Pc;npty A i-?'ful1.1??) producer `I co?r.d f? A Ve?pty?Pful1 A j?Vc.?pty.1-i) cons?cr (i A ?(k]--Hfc:cA[k])), 1'. do (I A IC A j'4 A Vc.Tpty-Pfull A j?Vcn.pty.l) hc?in awlit full?O th?n bc?in fuull-1; P?j11:?Pfu11?1 c.'.?; (1 A IC A 3< A Vc?pty?PfuI1-1 A j?'cflpt)'.1 A Vfu11?Ve.Tpty)O) y:?bur?cr[j nod ?); (1 A IC A j?'! A Vcr..pty?Pfu11.1 A j-Ven.pt>.1 A a?ait true thcn bo?in cmpty:?cn.pty.i; Vcn.pty:?Ve?pty.1 end; (1 A IC A 3l'1 A Vcopty?PfuI1 A j'Ve:npty.l) en (I A IC A 3?!.?) (B(k]?f(g(A(kJ)), 11) (Cbuffer(k wed .\`]?gCA[k)), VcoptyI?1 A 1<3O? false. So no such a exists. Froofa of mutual exclusion will be discussed rnore extensively in Chapter 5. For now we close by giving an exanple of the use of mutual exclusion in a proof of partial correctness. Figure 3.15 is a rewriting of the program addl of Figure 3.8. lere, instead of representing x:.x+l as an indivisible statenent, it is written .15 a:-x x:-a.l where a is a local variable. Scrnaphores are used to guarantee mutual exclusion for the critical sections whid? operate on x . Figure 3.16 is an extension of this prograrn, using auxiliary variables. The proof of the interference-free property for the two parallel staterents ma?es use of mutual exclusion. For exa??le, to show that pre(sddl) (x'a"z A y-O A inCS!l)-l A I) is invariant over add2 we must prove (pre(addl) A pre(add2)) add2 (pre(sddl)) But preCaddl) A pre(add2)?false so this is the same as proving (false) sdd2 (pre(addl)) Now (false) 5 (false) can be proved for any statenent 5 as can he shbwn by induction on the structure of 5 . Since false P for any assertion P . (false) 5 (P) can also be proved. So in particular ?e can prove (false) add2 (pre(addl)) . ln general. an assertion ? add3: becin mut?x:?1; cobc?in SI: be?in P(rnutex): a: x; x:?a?1; V(mutex); end 52: begin p(n.?tex); x:.b?1; vcmutex); coend 68 end end Figure 3.15 The Pr0?r?? add3. 6S await nute.?>O then ??tex:?n.utex-l critical section i aw?it true then nutex:?mut?x?l In order to prove that this acconplishes nutual exclusion we will use an array of auxiliary variables inCS[l:nI . Initially. inCS[i)?O, lO thenbe?in eutex:-mutex?l inCS(i) --H1 end critical section i await true thenbe?in nutex:?mutex?l lnCS[i):?O end Figure 3.14 shows the program of rigure 3.13 with the auxiliarx variables. The assertion that inCS(i]?O on reaching the critical section code and 1 throughout the critical section is justified because there are no other operations on inCS[iJ . Similarly the assertion that I holds at all tires assumes that there are no other operations on nutex. The interference-free requirement for assertions in?process i is easily verified because each assertion is a statement about inCS[i) which is not changed in Sj if i 6 j and I, ?ich is invariant over the statements in process j Now suppose that there is so,e computation a in which S. and o+ i ,E j o+ are executing their criticsl sections at the sane time. 66 (trjc) beein nutc?.:?l: inCS:-O (l A inCSri]?O, i?l c&?cgin Si ?/ .1/ 5:' cocnd (false) end (false) (I A incS(i]?o) Si: while true do be?in (I A inCS[i)?O) noncritic?l section; (I A inCS[l]?O) await n.utex>O thenbegin ?utcx:-?utex-l; inCS(i]:-1 end; (I A inCS(i]?l) critical section i; (I A inC5(i]?l) await true thenb??in mutex:-eutcx.l; incstil:-o end; (I A incS(i]?3) noncritical section; (I A incS(i]?O) end (false) I - (mutex-(l ? inCS[k]) A e?tex>O A YjCinCS[j]-O or 1)) :nutcx and inCS are not changed in the critical and noncritical sections eigurc 3.14. .?utual Lxcluaion Program wit? Auxilia::" Variables. CHAPT?R 4 Th? RtSTRICTED PAPALLEL LANCtIACE (RPL) The prograrraing language prcscnted in this chapter is essentially a restricted version of the general parallel language of Chapter :?. The powerful await statemcnt is rcplaceJ by another. nore limited s>nchroni:lng statement called withwhcn. The use of shared variables is governed by strict syntactic requirements which guarantee that only one process at a ti:ne has access to a given variable. Since much of the co?flexity of parallel progran hchavior Is due to interference between processes accessing a commo,. variable. the result of t?ese restrictions is that R?L programs are aore Intellectually manageable than prograas written in CPL. They are also much easier to prove correct. The proof of a program in GPL requires that parallel processes satisfy the interference-free property; verifying this is in general an exponertial problen. The corresponding property for R?L programs. called o+Einisch'jr.esfrei. can be verificd in linear time. This saving is accomplished by restricting both the syntax of the language and the assertions In the proof. It is similar to the simplification of proofs when the undisciplined use of ?to statements is elininated. ?L is based on a parallel language defined by lear (Ho72) and is?si:ilar to one propased by Srinch hansen (Dr72a). bare gave a set of axiors and inference rules for his language. however they were not strong enough to provide proofs in a number of cases. The proof rules AO-A7 in Table 4.1 are derived from lloare?s but are stronger. 71 72 To?et??cr with A.?, thcy form a o+`cor.plete?' deductive syste.--H.. ror the partial corrcctness of parallel progras in RPL as will be shon in Chapter 6. Section 4.1 defines the s?'ntax or ?L and 4.2 and 4.3 g?ve Its semantics in terms of an interpreti?e rodel and axiors. Section 4.4 shows that the intcrpreter and the axio,..s are consistent. `tuch of this work makes use of results derived in Chapter 3. 4.1.TheL?n?ua?e. RPL is defined by adding two statements to the secuential language of Chapter 2. Parallel execution is initiated by the staterert resource r1(var?able list)ra(variable list): coberin ?1,?? ???n coend here the resources r1 ... r are groups of shared variables. and the 0 5. are statements to be e,?ccuted,in parallel. Again, no assu=ption is made about the way parallelism is iir.plementedo+ or about t:?e relative speeds of the 5. . it is legitirato to nest one parallel statenent inside another. The only restriction is that the resources in the two statements be distinct. 4.i.ucfinttion: Components T and T of 5 are in different I 2 processes of 5 iff 5 contains a statement resource rr : cobeo+',in 5 ?? 1/5 coend m 1 n o9 add4: be?in )`:??:--O; :t:tex:".; inCS[L):-inCS[2]:.o; fx-?z-O A inCS[1]?inCS[2]?O A I) cobe?in SJ ?, S2 coend end Si: fx.: A y-O A incs!1]-o A I) betin (x=: A y-O A inCS[1]?O A 1) a?it mutex>O thenhe?tn `r.?tex:??utex-1; tncs(1]:-1 end tx-: A ?O A inCS(1)-1 A 1) ?x-a- A y-O A inCS[i]?1 A ?) addi: x:-a.1; (x-=.1 A y-O A inCS(1?-1 A I) --H1; ?x-?+1 A y-1 A inCS[1]-1 A I) aw?it true thenbe?in rutex:-n:utex.1; incs[1]-o end fx-zsl A y-1 A inCS[1]-O A I) end (x-:?1 A y-l A inCS[1]-O A I) 52 is syT??etric: (x-yA=-OAinCS[2)-O?I) 52 (x-y.lA:-lAinCS!2]-OAI) I --H (:?tex-C1 ? inCS(k]) A r.?texLO A inCS(k]-O or 1) k-1 Fi?ure ?.?6 The Prora? ?dd4. r 70 in a critical section is invari?nt 0v4r sssigr?ents in ot,?er critical sections beca?ae t?e inv?riance test redt?es to (falae) S `?: Pro?,ram addl has auxiliary variables y and irCS The staternents ?ich manipulate these variables can be renoved using AS, givine a proof cf (x?o) add3 (x?2) he have only skotched tl? proof for pro?ra? add4; a cc?plete presentation would require verifying that every assiantent and a?ait in SI presened every assertion in 52, and vice versa. Even for such a small program this would be a lar,e task, and it is a task which grows cxponentially in the size of the pro,,raR?. Thus, croofa for GPL prograns quickly becone unmans:esble. In the next chapter we will introduce a parallel progrs.T?ing language in which nutual exclusion is provided syntactically. This renoves much of the corplexity in the interactions between processes and greatly airplifies the process of proving that a program is correct. `s 4.3.Defi?ti?n: A parallel s?ateacnt In ?PL must o?ey the followin? restrictions: 1) Var(S) .?(S) u V1(S) u . u "?(5) 2) No variable belongs to Core than one resource; 3) if x c R(S) x appcars in 5k oni)' in a wit!??a statement for the resource containing x A) If x appears In 5k x is either a local variable for or a reaojrce variable. These requirerents can easily be checked at conpile ti,te. Their purpose is to guarantee that two proccases cannot intcr?ere with each other by simultaneousi)' operstin? on any "ariable. Rule I requires that every variable is a resource variable or is local to acme process 5. or both. If it is a resource variable, it belon?s to exactly one resource r Crule 2), and is accessible only in a witbwhcn state- Cent for r Crule 3), which prevents two processes from using it siTultaneously. If it is a local variable for 5k it is not chan?ed in any ?i if I , so he reference in 5k is unanbiguous. If a variable is local to more than one process. it is not changed by any of theo, so there is no conflict even if two processes access it sI?ultaneoualy. In GPL it was necessary to limit the form of statements which referred to shared variables. For exanple, x:?x?l was not a legitimate state--Hert if x appeared in more than one'procVss. These restric- tions were required to ensure that the interpreter accurately modelled parallel execution. IA RPL these problems do not arise, since 6, 76 references to shared variables are sllowed only in crttical sections and only one process at a tiae car. execute a crit?csl section for a givcn resource. Stater..en?s lile x:--x.l are acceptable. even if x is a shared variable. I: AddS (Figure 4.1) is another version of the pro?rar. of Figure 3.i. lore withwhen statements are used to control access to the shared variable x Examnle2: Producer and Consurer sharing a bounded bufrer. Figure 4.2 shows a third solution (due to Ijoare [10721) for the producer and consuler problem introduced in Craapter 3. Note the similarity to the solution in Ficure 3.5. The critical socton in the producer can only be started when there is free space in the buffer (count,O do be?in outpointer:?(outpointer+l) aod N; this vaiue:-bufferoutpointer]; count:-count-I coend end ?iguro 4.2. Producer and Consumer Using a Bounded Buffer. 83 fP?) s ?q') of the proof of (Pj) Sj (Oj) bc only those variables ?hich process 5. has a right to access at 5 . Those are roughly, the local variables of 5. plus the variables for resource r if 5 is a coaponent of a critical section for r . For a precise definition of Ein?ischungsfrei, we need the concept of the proof- variables of a statement or resource. 4.12.Definition: Let 5 be a statenent and r a resource in program 5 with r declared in the parallel statement T and let T be the statement which irmediately contains 5 . Then Proof-var(r) o+ ?x: x is not assigned a value in T except in a critical section for r) lroof-var(5') variables of 5 V?(T?) flProof-var(T?) if 5'-5 is 5 is the kth pr3ceas in parallel statement T' o+ Proof-var(T?) u Proof-var(r)? if T' is with r when 8 do 5 - Proof-varCT?) otherwise. Note that Proof-varCr) includes all the variables which belong to resource r anJ may also contain other variables. The variables in Proof-var(S') are either local to the process containing 5 or belong to Proof-var(r) , where 5' is a component of a critical section for r 4.13.Definition: Suppose 5 is the parallel statement resource rrm: cobecin ?1?? ..,/S coend n 84 Then (P) 5 (?) is Einmisch'r,?sfrei iff it nas a proof in which I) all free variables in l(r?) arc elerents of Proof-var(r,) I < j < n 2) if 5' is a enopoflent of 5 , and (P') s' f?s') is a line in the proof, then all free variables in P' and Q, are in Proof-var(5'). The variables in Proof-var(5') arc exactly those wich cannot be chanped by another process when preCs') and post(S') are expected to hold, i.e, when 5' is ready to execute or has finishec 4.14,Lenma: Let 5 and T be statenents in different processes of a pro?rafl S' , and a he a computation for 5' . Suppose 5 ij current after a , or a finiahes 5 . Then, if .T is read>' to execute after a , T does not change a variable in Proof-var(s) Proof: Since 5 and T are in different processes of 5' , tl:ere is a stateacnt T'"resource r1,..,.rno+: cobe?'2, Tl//???//Tn coend with 5 a conponent of T1 and T a coaponent of T i ? Suppose T chanees v?riable x . Then x A Vj(T') , so if x c Proo var(s) it aust belong to a resource r with 5 a proper co.':ponent of a with?hen staterent ?l for r , T must also be a proper corponent 0 a withwhe for r because of t?e syntactic restri tions of ?PL, ?i ? , since they are in different processes, and both are in execution for a . This is not possible, so x ? Proof-v Rules A6 and A? are presented in a way `?hich nakes it easy to produce proofs which are inn.ischungsfrei. The pre- and post- assert 31 4) If T is in a. (i>l) the variables in r aro not referenced in T Proof: r is bttsy for a iff a critical scction which l1sea r ja in execution, and this can only happen if a with?h?n staterent appears in a and is not finished by a . Then a can be written in the form above, satisfving 1-3. To see hat 4 is also satisfied, recall the a)?tactic restrictions of Definition 4.3. If T uses a variable froa r , T must be a component of a withwhen statement for r But then if T appears in a1 o critical sections for r are in execution at the same time, and this is not possible. ?. Ax?oms an? Interence ?ules. Table A.l gives the axioms and inference rules for the restricted parallel language. They are similar to the axioms tor parallel progr,as given by Iloare (1072]. Ilowever, Iloare does not provide for auxiliary varisblea, and his version of A7 is more restricted in the variables whicI, can be used in assertions. AD-AS and AS are the sar'o as the correstonding rules in Chapter 3, while A6 and A7 give the senantics of the two new stste:ents. Both rules use the resource invariant ICr) an assertion which describes the acceptable states of the variabl?s in resource r . A7 includes the provision that the proof of f? ) s ( be Einmischun,,sfroi. This condition is related to the i i interference-free requirement for GPL programs, but it is oore easily verified. It requires that the variables used in each line AO conacquenco (P')5(r)PFr0'?v (P) s (Q) Al saaI?nn.cnt (pX) X'?L fP) A2 null (?) ? tp I A3 Conposition ?)?23`?n?5n??,..l? (P1? be?ir 5 o+.. 5 cnd n --H (P A 1? 5 `0' `P `. `B) 5, (Q) A4 altcrnation (P) it B t!?cn else ?2 ??? AS itoration (PA1)5`0) (P) `h'le 11 dos (0 A?B) A6 critical ??????? (0AIA1(r))5`9A1(r)) (0) with r w.?en I ?o S (Q) (0?) 5. (Q.) is i??ischungsfrei, lO do be??n out?oint:"(outpointer+i) mod ?.`; y:?buffer(outpointer]; count:.count-1 coend end end B[j):--Hf(y) Pi:ure 4.4. Computation of 3[k) - fCg(A[k])). k - 1 35 of the parallel statement will usually contain an assertion shout the local ?`ariablcs of each process (Vk) and an asscrtioh ahout each resource. The resource invariant holds when parlIel execution begins. and is presened by each critical section. Since its varishles are only ?oaified inside critical sections., this means that the invariant holds whenever no critical section is in execution; in particular it holds when parallel execution ends. Inrerence rule A6 reflects the fact that a process may assume that the Invariant holds when it gains access to the resource. but that nothing else is known about the shared variables. Ihen the process leaves the critical section it cannot ,?ske any assumptions about the state of the resource, since that ;nay be chaneed unpredictably by another process. ?xamfl?e1: Figure 4.3 gives an Inforual proof of the procram add6 which is o'?tained from addS by inserting an auxiliary variable y(1:2] . The program variables are x and y , and the variable classes of Detinitions 4.2 and 4.12 are: Var(par) R(par) - (x) Proof-varCrx) - (x.y(l),y(2)) V1(par) - (y[l]) Proof-vsr(adda) - V2Cpar) - (y(2]) Proof-var(addb) - The reader can verify that the proof is iinelschungsrrei, Repeated application of AS :ives a proof of (x-O) addS (x-2) o+ o+/. he?inCO!.i?nt )l). y(2] are a?xiliary variables; y[i) :?y(21 :0; (y[l]?O A >(2]?o A l(rx)) resorcL rx(x): cobc?tn adda: with rx do (y(l]-O A !(rx)) be?in x:??.l; y(l]:=l ed fy!1]--H1 A l(r?)) I, end addb: with rx do (y[2]=O A I(rx)? bc?in x:"x+l; y(2):?l end ?y[2)--Hl A ICrx)) coend (y!l]?l A y[2?--Hl A I(rx)? J(rx) - y[l] ?i;urc 4.3, An Informal Proof of (x-O) add6 `.x-2) 91 (?-reccivc??l?l A ?<`.i??) con5??ncT: ?hi1e Jr do (j?r?cciveJ?1 A Jr A B(k)?f(g(At??)). 1O do (J?rcccived?i A Jr! A B?k??f(g(A(?l)). ljk1)0) fg3: bc?incort,.ent sent and receivod are auxiliary variables; inrointer:?outpointer:?count:?O; i:--H5 :--Hl; sent:?received:-O; (I(Bufaan) A i?sent.l-l A j-received.l?l A al>o) par f a: resource Bufaan(inpointer,outpointcr.count,buffor): cobe?in producer ,/ consumer coenl (I(Bufman) A received?1 A 1l(k]-f(g(A[k])) 1:-i`I) erd (??k]--Hf(?CA(k])). L--Hl>1) uhero l(Bufman) - (Osc?untO A aw?O A (ar?O V aw-O) ? false Also. writers exclude each other. since wrlting[i)'l A writing(j].l A I(control) ? aw?2 A awO thcn T2 - ?sit true then Then. N i i D1 - A (post(Si) V (pre(T1) A mutex (inCS[l]-inCS(2)-inCS[3)?O A I) mutox-l 117 nostedl: be?tn ni:?m2:-l; outer: cohe?in SI: be?in P(ml); critical section 1, V(ml) end end S2: ?e?jn P(ml); critical acction 2; inner: cohc?in 521: bc?in P(?2); critical a?ctinn 3; V(m2) cnJ 522: be?in PCm2); critical section 4; V(m2) cnj coend; coend end Figure 5?6. Neated Parallel Statements 1 118 nc?tcd2: h(?in ml:?; outcr: O)??in 51: h???n ?ait1: P(rrl); critical accticn I; V(ml) `I cnd inncr: cobcv?n 52: bcgin wait2: P(tnl); critical section 2; V(ml) coend coend end 53: be?in ?ait3: P(ml); critical section 3; ond end Fi?ure S.7. \?ested Parallel State?ents 2. 121 rcsojr?e rl.r2: cobe?in' 51: with ri do with r2 Jo ?I 52: with r2 dowith rl do coend If 51 acq'Jires ri and 52 ac?uires r2 neither statement can proceed and the program is desdlockej. 5.16.Definition: An RPL program 5 is deadlock-free 1ff there is no computation for which 5 is deadlocked. There is a well-known technique for avoiding deadlock; each pracess must request and release resources in some standard order. In an RPL program this C3fl be accomplished by reatr?ctiona on the nesting of withwhen statements. 5.17.Theorem: An RPL program S is?deadlock-free 1: its resources can be put in an order r1 r. such that no withwhen statement I 1m using r1 properly contains a wthwhen statement using ri With 1 k k i but this contradicts the choice of i So 5 cannot be deadlocked. 124 Of courae, there are ot.?er o+?ys of avoiding deadlock, but the tcchniq.?e above is especially convenient since it can b checked syntactically. Note that a pro?ra.? with no nested cr?tical sections is Jc.idlock-?rt.c. Ix.r.nlc: Figure 5.9a and b gives two additional solutions to the dini?o+, philosophers problem; they are also due to Ifoare [Ho72]. The first is in danger of deadlock, since if the five philosophers sie'ul- taneously pick up the fork on thc right no one will be able to pick up his second fork. The next solution avoida this problen. by rollowing the discipline of Theorem 5.17, ao it is deadlock?free (the order is forko, forklforl4). `lowever, it has the undesirable feature that when philosopher 4 is eating, the other four esy be forced to wait?until he haa finished. The solution in Figure 5.2 is preferable, because it does not stop a philosopher from eating unless one of his neighbors is eating. 5.2.3.Prog'ranilockin,inP?L. Deadlock is one way in `?hich a program can be blocked; blocking can also occur if all procesans are waiting at with?hen staterents for conditions which are not satisfied. This situation is related to blocking in GPL prograns as presented in 5.2.1, but it is coplicated by the fact that the statement with r when 3 do 5 can be blocked either because r is busy or because 3 is false. l?hen a deadlock-free program is blocked we can sss??e that at least one statement is blocked because 3 is false. fi A inCS(i)?O) Si: be?in (I A inCS(i]-O) %`sit i: P(¶.1),' (i A inCS[i)?l) critical section i; (? A inCS(i]-1) (i A incs(i]?O) end (1 A inCS[i]--HO) ?2l I --H (il --H 1 - ? inCS[i1 A ml>O A (ON ? sentN Dcconsusaer) - pre(rernove) A count\.')) A (received-M V (roceivcd<'l A count\?) A (received-.' V (received<'I A countN A rcccived-M A count-sent-received if N>O ? count>N A countO false So fl A 1)2 A 1)3 false if `-`0 This loads to the reasonable rc?uirc?ent that the buffer used for ca??unication ru..at have at least one' element so that the prograa csr?ot be blocked. ?estedPa??St??er?.,cr.t5. Theoroa S.ln applies only to proera,.s in which there are no nested. parallel statements. The theorern below is more ?enoral, and is analagous to Theorem ?.l4. S.23.T?eorem: Lot 5 be a deadlock?free RPL progr?T. with asae?tion functions pre, post, and I for (P) 5 . For each parallel component T = resource rrm cobe'in T1/?.. /iTn ecend let Si k be the parallel 5tate7?enta in T. which are not proper co.Tponcnts of another parallel atatemon inside T and let T1. be the withwhen atateoents of Ti which are not contained in any sk? Define 0(T) = tr: r a sir'?le resource declared in a statement which contains T) - ?l? if r c 0(T) - true, otherwise 13S wax while other? reqL:ire a r?del in which there are deftnitc ruics for sc?e?jline competing processes. I?pefully, future work will broaden tbc range of properties which can be proved with axiomatic iothoia. Cii?PTF.P. 6 CO\?lSTENCY A.fl CO?'PLET??ESS OF ThE DEDUCTIVE SYSTE'? Throughout this thesis two different nethods have been used to describe the senantics of a program?ing language. The de2uctive syste:, consistint of axiors and inference rules, is convenient for proving that a prograa performs correctly. The interpreter is a mudel of the wav statements are executed on a real nachine, and provides considerably more detail than the deductivo systen.. In this chapter we discuss the relationship bctween those two methods. Either one could be ta?en as the primary definition of the secantics of the languages. Here we have chosen the interpreter as the basic definition, since it is closer to our intuitive unerstanding of what parallel pro?ra=s o+`mesn'?. Fron this point of view the consistencY, theoren's in Chapters 2. 3, and 4 state that the deductive systen. is correct, in the sense that it accurately describes the results of program execution. Section 6.1 is devoted to rather lengthy proofs of these three theoreos. Their meaning could be summarized as "anything which can be proved is trj&'. The converse of consistency is completeness, or "anythin,, which is true can be proved". The axioms and inference rules give signifi- cantly less detail about P?0?r5?? execution than the interpreter. If the deductive system is complete with respect to the interpreter, we are justified in saying that no essential information is lost by using the axioms. Section 6.2 considers the completeness of the deductive 136 133 S.3.Ter?instlon. Progra,. terrinsion is an irportant property for both p.?rallel and scquential prorraas, although th?r arc corrcct paralici program',; whic? do not terminate, Vario?s techni?ues have been suggcated fcr proving termination of sequential progres (oar [IIo?9], `,¶anna [`ta741), and the sane nc',?ods can often be applied to parallel programa. A sequential prograo can fail to terninate for two reasons: an infinite loop or the execution of an illegal operation such as dividing by zero. With paralici programs there is an additional possibility: the program can be blocked, (It is e"en possible that a program can be blocked for one co?putation and loop infinitely for another.) iut if a program cannot be blocked, termination can be proved just as it would be for a sequential program. One sppr?sch to proving terninttion is to show that each statement terminates provided that its primary components terminate. We ?`ill not attempt to prcaent general rules for doing this, but will give autficlent conditions for pro?ing that a parallel statenent terminates. For similar conditions for sequential statements see ,?1anna (?a74]. S.22.Definition: T ??esconditiona?iv if it can be provcd to terminate under the assuaption that it does not become blocked, S.23Theoren: If T is a cobe?in statement ins GPL or I:PL program S which cannot be blocked, and T is not a component of another parallel statenent, T terminates if each of its primary components terainates conditionally. 134 Proof: Suppost. T does not tLTT\.?nate. None of its processes can loop Lndcfinitely, so after a finie tise each one either finishes or is hlocxed, At that point T is blocked, and since it is not a propcr cowponent of a parallel statement, 5 is also blocked. Since this is impossible, T must rerminate. L-Y.an?le: Consider the producer and consueer prmgram in .e?gure 4.5, We have already proved that it cannot be blocked, so we need only show that the producer and cons'j;er processes terminate conditionally. Assuming that the operations required to corpute g(A(il) do not stop execution, the producer rust cither becore blocked or perform M iterations of the loop and terminate. So the producer process terminates conditionally, and the consuner process is similar, By Theorem 5.23 the statement par f g, and thus program fg3 must terminate. Note that in this example the producer can be blocked at "add" when count'N . `owever, it cannot be blocked there forever, since the consumer is not blocked and will eventially renove a unit fr? the buffer. In ?eneral conditional termination irplies termination if a process can only be blocked temporarily, as is the case here, This concludes the discussion of correctness proofs ?hich include pro?erties besides partial correctness. There are many other pro- perties which could be considered: priority assigr?ents, progress for each process, blockin cf some subset of the processes in a program, etc. Many of these properties are difficult to define in a uniform 139 in Chapter 2. in conn?ction ?ith the rule of consequence). This censiatency ir-plies that if P ? Q and P is true. then Q is also tn:e. Proofcf1): Induction on the structt:re of 5' If ?` is an assign. null or w?ile statement, s' T and I) is true by ass??ption. If 5' - be?in ... ___ and by induction post(5 ) 5n e,.d a oust finish 5n n is true after a , Since poSt(Sn) ? post(S') post(S') is true after a . If 5' is if B then ?l else S2 a finishes either or In either case. post(Si) is true after a , and P05t(Sj) ? post(S') . so post(5') is true after a Proofof2): By Ler?s 6.2, 5' - succesaor(T) . Considcring nefinition 6.1. either 5' - while a do T' or 5' follows T' in a se4uence of statements. In either case, a finishes T' . ma&ing post(T') true after a and postCT') k pre(5') - Thus, pre(S') is true after a 6.4(2.15)Theorem: If pre and post are assertion functions for (p) 5 (q) . 5' a cooponent of 5 and a a computation for 5 from a state 5o satisfying pre(S) then 1) If 5 is ready to execute after a , pre(S') is true after a and 2) if a finishes 5 postCS') is true after a Proof: Use induction on the length of a . If a Is empty, 1) is satisfied because 5 is current initially and pre(5)(s0]?true . 2) does not apply. If a a'T consider the cases for T a) T is a:-" . Then a'T finishes T pre(T)(value(s0,a')1?true by induction 140 postcT)XEivsiueC50,a')1?true since pre(T) ? postCT)XE post(T)(value(50.e))=true since oxecuting x:"E assigns tho value of f to x ay Lenma 6.3, I) and 2) arc satisfied. b) T - null By induction preCT)(valuecs0,a')i=true Now preCT) ? post(T) and T does not change any variables. so postu)ivaluecso,a))=true Applying Lerma 6.3 shows that?l) and 2) are satisfied. c) T is be?in T1Tn?cn? . T is current after CL' so by induction pre(T)[vslue(s0.e'))"true Then, preCT)[value(s0.a))=true since T does not chanse any variables, and pre(T1)[value(ao.o))?trUC since pr?.(T) ? pro(T1) . Thjs 1) is satisfied. and 2) does not apply. d) T is if B then T1 else T2 . By induction precT)(vaiue(ao.e')J true . If a?vsluecs0.e?))?tr?e T1 is current after o'T Also. (pre(T) A B)(value(s0.a'T))?trUC giving pre(T1)(valuecso.C)l "true . If ?B!valueCso.o?)]=true , T2 is current after a'T and pre(T2)!value(a0.a))?truC . Thus 1) holds and 2) does not apply. e) T is while B do T1 and ?(valueCs0.a?)1"trUC . This is handled in the same way as case f) T is while B do T1 and B(valueCs0.n')l.?false. Then a --H a'T finishes T . and poatCT)(Yalue(so.e))?truC since (preCT) A ?B) ? poat(T) . Then by Leema 6.3. 1) and 2) are aatisfied, 137 syster for RPL. 1?e will show that the a.?ions a?d infcrence rules given so far are cor?lete in a special scIse defined by Cook. 6.1.Cor.siste,.cy. In this section we will give proofs for Theorena 2.15. 3.15, and 4.18. thus establishing the consistency of the deductive systers and the interpreters for SL, CPL, and RPL. The proofs follow the same pattern in all three cases. ocouentiaiLd(??u???. The proof of Theorco 2.15 (and also of the other consistency theore?s) requires a rather tedious analysis of computations and program states. A few preliminary definitions and lemmas are necessary. The following definition gives a characterization of successor(s), the statement which is next to be executed after S finishes. 6.1.Definition: If 5' is a component of an SL program 5 and a primary component of the statement T then suc:cessor(S') - T if T - while B do 5' -?T' if T - be?in ... 5'; T' ... en? --H aucceasor(T) if T - if B then 5' else T' if B then T' else 5' be?in .. 5' end if S' - 5 i.e., 5' is not a primary component of any T . 5 baa no successor. 38 6.2.Len.oa: If a is a cor?utstion for an SL trograr. S and a finishes 5 then sjccesaor(S') is current after a Proc..: his anounts to sho?ing that program flow in the interpreter follows the usual pattern. Use structural induction. starting with 5 5 - In this case a cxecutes 5 and na ataterent is current after a )uat as 5 has no suctessor. .?ow if 5 is a prir.?ry component of so::e statenent T consider the cases in the definition of aucccssor(S?) . In the first two cases. next(s.T) creates a control tree in which 5 is a son of succeasor(S?) . Thus. when 5 is finished, succeasor(S') is a leaf in the control tree and is curre.?t. In the l:::at case. when a finis)'es 5 it finishes T , and by induction successor(S?) - succeasor(T) is current after a The next lemea will be used to show that pre(S) and poatcS) hold at appropriate times during progra? execution. - 6.3.Le??s: Suppose pre and post are assertion f?nctions for fP) 5 and T is an assign. null. or while statement in 5 . I a is a computation for 5 which finishes T and post(T) is true after a then 1) if a finishes 5' post(S') is true after a 2) if 5 is current a?ter a pre(S?) is true after a Proof: The proof of this lenr...a relies on the consistency of the deductive systea for the data types of the program (this was discussed 143 6.10.(3.IS)Theoren: If S is a GPL progran. with assertion functions pre and post for (P) s (q) . S is a component of S and a a compt:tation for 5 tro.,. with P(s0]-true , then I) if 5 is current after a , pre(S') holds after a 2) if a finishes 5. poat(5') holds after a Proof: By induction on the length of a . If a is empty. pre(S)(value(s0.a)]-pre(5)[s0]-true by asauTption. and no other s:atement is current after a . Also a does not fii?iah any statement, so 2) does not apply. If a - a'T there are two cases to consider. Cast1: 5' and T are from the same process. This is just the same as the equential problem. It is only necessary to consideF tha two new cases of T g) T - cobegin coend - Then each Tj is current after T1 ?I...,/ Tn a T and since pre(T) ? ?A preCT1)). pre(Ti)!value(50.a)].true. This ?ak'es 1) hold, and 2) does not apply. h) T is await B then T . By induction and the fact that T is ___ --H 1 ready to execute after a' (pre(T) A B)(value(s0,a')1-true and pre(T1)[valua(s0.a')]-true , since preCT) A B ? preCT1) . Now value(a0,a'T)-execute(value(a0,a). T1) and by Corollary 6.6, post(T1)[value(s0.e)]-true . But then postCT)(value(s0,a))-true since post(T1) F postCT) . Applying Le??na 6.9 shows that 1) and 2) hold. Case2: 5' and T are from different processes. Note that if 5' is current after a'T 5' is current for a' and by induction 144 pre(S?)[vale(a0.??)jtr?c. If T is a null if, he?in, ?h'.1e, or larallel statenent, t?c variables have the sane val?e in e'T as in ?? so pre(S')(valiie(s0,a)]'tne 1? T is an assi:r.nent or a?aIt staterrent (prc(T) r. pre(S?)) T fpre(S?)) can be proved (this is the interfcrence-fr?e property). .`?w bv nduction, (pre(T) A pre(S')) (va:utfs0,?')] true , so pre(S?)(vslue(s0,a?T)]-true If o'T finishes S , 0 also finis.?es S , and by induction post(S?)[value(s0,u?)]-true . O,.ce a2ajn the interference-free property guarantees that postCS?)(vaIue(s0,eT)]?true . Thus 1) and 2) hold in case 2. 6?1l.(3.16)Corollarv(consistencvofAO-A7forrPL): If S is a CPL program and (P) s (Q) can be proved, it is true in the interpretive model. Proof: In Chapter 3. 6.12.(3.20)Theoren.(consistc?cyofASforCPL?: If S is a CPL program and S is a reduction of S which satisfies the anxil?ary variable rule, then (P) s (Q) is true in the model. Proof: In Chapter 3. TheRestrictedParallelLaneua?e. Consistency for tho RPL deductive system can be proved in ??uch the saLe way as for CPL. 141 6.S.(2.16)Corollary: if (P) s (q) can be proved. it is true in the interpreti?e nodel. Proof: Gi?en in Chapter 2. This is the basic conaistenc)' result for sequential progra:sa. The following coroLlary will be uacful in the discussion of GPL progr3=?s. 6.6.Corollary: if S' is current in prograa state a and pre(S?)(s]-tr?e then postCs')(execute(s.S')]=true Proof: Recall from Definition 2.13 that execute(a,S?)?value(s.e) ?ere a executes S . Applying Corollary 6.S yields post(S?) value(s.m)].true rheGeneral?arallelLafl?us?c. Next, we prove the consistency of the deductive system for CPL. The first step is to generalize the definitions and lemmas of the last section to include await and parallel statemcnts. o.7.Definition: If S' is a component of a GPL program S , and a primary component of T successor(S?) - aucceaaor(T) if T - await B then S or cobegin o+.. ... coend - successor(S?) from Definition 6.1 otherwise. 142 6.8.era: If m is a corputatlo:: or a GIL proarsa 5 . a finishes 5' , and a stateaent from the ssre process as 5' is current after a then that statement is succ?'ssor(S') Proof: Essentially the a:sr? 55 Lewna 6.2. There are two new cases for where 5' is a priaary corponent of T . If T is a parallel statemcnt, finishin4' 5, will not n?cessarily finish T since other processes of T may still be in execution, In this case. however, no statement from the same process as 5' is current. If a finishes T , by induction succcasor(T) successor(s) is current in a If T is await 5 then 5' , the interpreter executes T indivisibly, and 5' never appears in a computation. So this case does not occur, 6.9.lemma: Suppose pre and pest are assertion functions for (I) 5 (Q) . and a is a coaputation for 5 which finishes T , where T is an assien, null, while, or await statexent. If postCT) holds after a , and 5' and T re from the same process. then 1) if a finishes 5' post(5') is true after a 2) if 5' is current after a preCs') is true after a Proof: 1) The same as Lemma 6.3, with two new cases for 5' . If 5' - aw.?it..,, then 5' --H T and 1) is true. If 5' - cobe?in 5 co?nd and a finishes 5' a finishes each 5, . By' n 1 induction, CA post(5.)) is true after a , and since (A post(Sj)) i I i F post(5') , postCS') is true after a 2) Saae as Lemma 6,3. 147 Also B(?'.?lue(a0,a')]-true , ani by inductian pre(T)[va1uc(s0.a')i?true Then pre(T1)(value(s0.e)).true . since (prc(T) A B A 1(r)) ? pro(T1) and startine T does not modify any variable values. So 1) holds. and ,) does not apply. Case2: 5' and T are from different?processes. Note that if 5' is current for a'T (or a'T finishes 5' ). S' is current for a' (or a' finishes 5' ) and by induction Pre(5')(value(s0.e')]?true (or post(S')[vslue(s0,a')]?true ). By Le?a 4.14. T does not change a variable in ?roof-var(5') so pre(5')[wslue(s0.a))?true (or post(S')(vslue(s0,e)]?true ) Finally, we must show that 3) holds. Let T' be the parallel statement in which r was declared. If T' is not in execution for a1T 3) does not apply, so assume T' is in execution for a'T . If ? Is current for a Pre(T')[value(s0.a)]?true and 1(r). [va1ue(s0.o)]?true sinca pre(T') ? 1(r) . If not, T' is in execution for a' and by induction, 3) is satisfied for a' . There arc two ways in which a'T could fail to satisfy 3). a) T changes a variable which is free in 1(r) . But in this case r is busy in a'T so 1(r) does not have to be true. b) a'T finishes a critical section for r i.o., T nakes r not busy. But then from case 1 above, I(r)(value(a0,a)]?true 6.1?.(4.20)Corojjarw(consistencvforRPL): If s is an RPL program and (P) s (Q) can be proved, it ia true in the interpretive model. ,yA, 148 Proof: In Chaptcr 4. The consistency results of this section imply that if fP) s (Q) can be proved. it is true for the interpreter. If the interpreter is a good model of parallel e?ecution on a resl osehine, then the deductive systee is also valid for real eachines. There are several ways in which a real in.ple.?entstion night differ from the interpreter. The rost fur.?anental is that the interpreter does ..ot allow true parallel execution, but siulates it by nondeter:,snis:. In this respect it is a model of nultiprogrs??ing, but not of cjlti processing. In Chapter 3 and 4 we have argued that the languages GPL and I?L are defined in a way which guarantees thst nondeterninism and parallelism ive the saae results for all prosrama. A second possible difference is in the treatnent of expresslons which are normally considered to be undefined, such as those involvin: division by zero; this was discussed in Chapter 2. The interpreter gives these expreasiona an arbitrary value, but it would also be reasonable to stop execution as Soon as such an express?on was encountered The axioms and inference rules are also consistent with this treat:ent of the problem. since any?fornula (P) s (Q) Is true if S does not terminate. A third area in which a particular implecentation might differ fro?. the interpreter is by speefying in more detail the way parallel processes are scheduled. For example, processes which are cor?eting for a resource might be guaranteed to receive it on a first-cooe, first- 145 6.13.nefinition: If S is a componcnt of an RPL program 5 and a primary co?ponent o T successor(S?) succeasorCT) if T is resorce rrm cohetin ... .. coend or with r when 8 do 5. succcssor(S') from Definition 6.1 otherwise. 6.14.Lem,s: If a is a cooputation for a GPL program 5 which finishes 5 and a statement froa the same process as 5' is current after a then that state?ent is succcssor(S') - Proof: As in Lenma 6.8. conaidcr the cases for T , where 5' is a pri?sry corponent of T . If T is one of the five sequential stste?.?nta, or a cobe'in statement, the proof is the same as Lemma 6.8. If T is wit', r when 8 do 5' , a finishes 5' , and by induction successor(S') - succesaor(T) is current after a 6.IS.LeT.. Suppose pre. post, and I are assertion functiens for (P) 5 (Q) and T is an assignment. null, or while statement in 5 If a - a'T is a computation for 5 which finishes T , and post(T) holds after a , than 1) if a finishes 5' . post(5') holds after a 2? if 5' is current after a , preCS') holds after a Proof: I) Consider the cases for 5' . If 5' is assign, null, while, berin, If, or cebeein the argument is the same as for Lemma 6.9. 146 If 5 is ?ith r `hen I :0 ?io+ a finishes ?i and by 1n?L?ctson p3St(S1) holds after a . Since post(S1) h post(s?) post(S') hol?s after a 2) `same as for Le??a 6.?. 6.16,(4.l.?)Theoren: Suppose 5 is an RPL proersa, and pre. post, and I are assertion functions for (P) 5 iq) . If a is a co?putaticn for 5 from state 5n with P[a0]?true then 1) if 5' is current after a preCS') holds after a 2) if a finishes 5' post(S') holds after a 3) if resource r is declared in a statenent which is in execution for a and r is not busy for a 1(r) holds after a - Proof: ly induction on the len?th of a If a is empty. pre(S)[value(a0.a)]?true by assuaption, and no othcr atate?ent is current in a - so 1) holds. a does not finish any statements, so 2) does not apply. If 3) applies, 5 must be a parallel stateoent in which r is declared. and 3) holds because pre(s) ? 1(r) If a aT we first shod that 1) and 2) are satisfied. Consider two cases: Case1: 5' and T are from the same process. This is the same as case 1 of Theorem 6.10 if T is cobe??n or one of the five sequential statements. The other possibility is that T is with r when B do After a , T' is current. Since T is ready to execute after a' , r is not busy for a' , and by induction I(r)(valuc(s0.a')]-tn?e ISI for GPL and SL are also relatively complete but that will not be proved here.) As a first step we prove relative completcness for programs in a language which contains the n.?tural nuabcrs with <,-..,. .?nd (concatenation, to be defined shortly). The language I. used for assertions in a program proof will be the first-order predicate calculus language whose nonlogical syabols are Concatenation is an operation which is useful for representing sequences of natural nuabers: it is included in the progra?ing language operations because it will be necessary to introduce auxiliary variables which store sequences. 0.55.uCtinitlon: The operation of concatenation, written xIJy , is defined by xIJy lO-x o+ 2 if y 0 - (lO*x o+ 1)1 (y-l) , otherwise A rinite sequence n1,n2 nk can be represented by tho integer (?.?((0IIn1)I?n2)...)IIn? . here each nuaber n. in the sequence is represented as n. l's followel by a 2. For examplo, the sequence 2,0,4 is expressed as ((0I?2)II0)I?4 --H 112211112 Note that 0 represents the null sequence. 6.19.Theoren(Relativecomplete.??ufRPL): Let T be a program in a version of RPL whose data domain is the natural numbers with <,?,..`, and `74% 152 L?t he ?on.;?lctc p?u?f syste. for t:?e natural nunbers (D will not be ?ffecti?'e). Then if (P) T (q) i)L rue in the inter- pretive nodel it can be proved usinp D and AOA.?. Prouf: Sections i.2.l.6.2.3 are devoted to a proof of this theorem for t??e case in which T contains at float one cobt?in statement. If T contains more than one cobe?in the principle is tl:e st?e; although the details are more corplicaced. The approach used in the proof is outlined below: 6.2.1. Construct a progran. T by sdding auxiliary variables to T Show that (P) T (Q.? is true in the interpretive model. 6.2.2. Define pre post and I for T. 6.2.3. Show that pre. post and I are assertion functions for (P) T- (Q) which implies that (P) T. (Q) csn be proved. Then AS can be applied to remove auxiliary variables. givin: a proof of (P) T (q) The crux of the proof is defining assertion functions preCS) post(s) and 1(r) which depend only on the variables in Proof-var(s) and .mroof?var(r) . respectively. In program T which contains a single cobe?in statenent T0 - L resource r 0 r?1: cohe?in L1: T1 /?.../? L?: T?, coend Proof-var(r?) - (x: x is not assigned a value in T0 except in a wit?hcn statement for r-) Proof-var(s) - (variables of T) if 5 is not a proper corpenent of T0 149 served basis. Such an implementation is consistent with the interpreter. so it is also consistent wit.? the axioas anci inference fl.les. All of this suggests that the dcductive system accurately describes the behavior of parallel programs when exccutcd on a real ?achine. To prove that this is true for any particular machine requires a proof that the implementation of the language on that machine is correct with respect to the semantics defined by the interpreter. Such a proof would be a major undertaking, but a aimilar result has been obtained for the implementation of a sequential language [?i72) 0..?orT)Ieteness. The last section established the consistency of the deductive system and the interpreter; now we would like to show that the deductlvc system is also complete with respect to the interpreter. Unfortunately we cannot hope to do this in ceneral, as the following e?ample shows. If the progra::??ing language SL operates on data types which include the natural nur'?ers and the standard operations on them, it can be used to encode a Turing machine. Let 5 be a program which encodes a Turing machine that does not halt on any input; then 5 does not terminate from any initial state. ?or such a program (true) s (false) is trivially true. The set of Turing machines which do not halt on any input is not recursively enumerable, but the set of?provable formulas is, so in general (true) 5 (false) cannot be proved. Although the deductive aystem cannot be complete for any programming language which includes the integora, this does not' necessarily mean ISO that t.?e a\.ioms and inference rules arc inadequate for describirt the pro?rarming lan?uaee. Part of the preblen is the fact that there is no conplete first?order deJuctl?'e systen for the natural n?bers. Recall the fore of AO (the rule of consequence) (P.)s(?`;pFP?.fl'?Q Au: iP) 5 In order to usc this rule, it is necessary to prove 1" fran P and Q from Q, using sore deductive syster 0 for the data types of the prollra.?sing language. hen we presented AC in Chapter 2. we rade no ass?n.ptions about the choice of n except that it is consistent with the data types of the language. 0 cannot be coeplete if the ?ata types include the natural numbers, by the Gbdel into--H.?pletenesa theorem, so the incumpleteness of the deductive syste.. for prosracain: languages is not surprising. ow suppose 0' is some complete proof systen for the data type? of the language (in general 0, will not be effective). If using 0' in AO yields a c?-.plete proof system for the progr?Thrning language, we will say that the original deductive system is relativelvcorilete. Relative completeness suegeats that the axioms snd inference rules give "enough" inforation about progran execution, and that the incorpleteness of the deductive system is due to the incompleteness of D This approach is due to Cook (Co7S), who used it to prove the relative campleteness of a deductive system for a sequential language. In this chapter we give a proof of the relative coepleteness of AO.A8 for RPL programs with a wide class of data doisins. (The rules iss precedes 81, or 81 precedes Al. or their execution overlaps. The same is true for A2 and 82, so the 6 posaibilitica in Figure 6.1 represent all of the interesting cases. In order to prove (true) Aor? (Afirst"l v lfirat"l) , it is necessary to add auxiliary variables to Aor8. Figtrc 6.2 shows the sug?ented progran Aor8' and Figure 6.3 givca th? final variable values for the six conputations of Figure 6.1. N?te that the final values of the variables Altiae Altine Iltice . 82time make it >ossible to reconstruct the order in which atatenents were executed. The rule is that if xti:eAltime A 82time>8ltiae 2. Alti'e?B2tlmo A 8ltime?A2time 156 AorB : b?rir Atime:??tine:?r1ti?e:?r2tir..e:?O; AItime:?A2tin.o:?Blti;no:?82ti?e:.O; doneAl :?doneL1 =0; re?ourcc rI(doneA1.r1tirne),r2(done?1,r2ti:r.e). cobepir A: bc?ln Al: with ri do bein Altine:=1.nax(Ati?e?r1time); Atin.e:=rltioe:=Altire; doneAl:=1 end 1/ end A2: with r2 do bc?in A2t?:ne:=i?oax(Atime,r2ti?e); Atioc:?r2tioe:.A2tiee; 8first:"done8l end end 8: begin 81: with r2 do be?in eltine:=1.?ax(8tine.r2tiee); Bti?e:-r2time:.8itime; doneBi -i coend end 82: with ri do be?n 82tirr.e:-i.?ax(Btire,r1ti?e); Bti:re:-r1tirne:-82ti?e; Afirst:-doneAl end end Figure 6.2. Prograz? Aor8?. 153 Proof?var(T?) (a: no statement of Tj ? 6 k assigns a value to a) Proof-var(S) - Proof-var(T?) ? ( u Proof-var(r)) 5 a proper component ot a ?itI?hen for r The details of the proof depend heavIly on the operation of the flPL interpreter. and the reader may wish to review Section 4.2, especially Definition 4.4 to 4.10. Section 6.2.4 considers the implicationa of the relative complete- ness theorem, and shows how it can be broadened to apply to the standard pro?rar?ing language data types. 6.2.1.Therru:??? In this section we will define a program T. by adding auxiliary variables to T . Before describing the general construction for T- however, we present a simple example which illustrates the techniques involved. Ex ?nan"ie-o+TheProtram,?or?. Consider the progran AorB in Figure 6.1. For this program (true) AorB (Afirst-l V Bfirst?l) is true in the intei?retive model, because any computation aJat execute Al before B2. setting Afirst-l or Bl before A2, setting Bfirst-l . This is illustrated in Figure 6.1 by listing several computations and the final variables values in each case. ?.`ote that not all coaputations are included. since Al and Bl, as well as A2 and B2, can be executed in parallel. Since Al and ni have no variables in coanon, the results are the same whether Al 6, 114 AorB: hein doneAl:-done8l:?O; resource rl(doneAl) r2(done?l): cobe2in A: be?in Al: with ri do doncAl:?l; A2: with r2 do 5firat:-?one8l; end end Computation 1. Al A2 al 82 2. Al 81 A2 ?2 3. Al 81 82 A2 4. 81 Al A2 82 1. 81 Al 82 A2 6. 81 82 Al A2 8: be?in 81: wit: r2 do donell:--Hl; 12: with rl do Afirst:-doneAl; co?nd linal Values Afirat Ifirat 1 0 I 1 1 1 1 1 0 1 ?igure 6.1. Program Aor8 and Sevcral Co?putations. 159 3. B2time>Altir.e Afirst-l 4. A2ti?e>Bltime Bfirst-l Aasu=?e AfirstAl . Then from 3 and 2, Altime>i2time from I, A2time>BltiDe and from 4, Bfirst-l . Thus, CPostCA) A post(B) A I(ri) A 1(r2)) ? (Afirst-l V Bfirst-l) The use of variables in the proof is legit?mate, since Proof?var(A) - (doneAl,Bfirst,Atin.e,Altime,A2tirne) Proof-var(B) - (doneBl,Afirst,Btime,Bltime.B2tlme) Proof-var(rl) - (doneAl,Afirst,rlti?e,Aitime,B2time) Proof?var(r2) - (doneBl,Bfirat,r2time,Bltime,A2time) The auxiliary variables Altime ... B2time arc particularly useful because each belongs to the proof.variablea of a process and a resource. Thus Altime for example, can be used in pre and post assertions for stateaents in process A , as well as in ICri) . Since the "time" variables encode enough information to determine the order of stitement execution, they make it possible to prove that if Al did not precede B2, BI must have preceded A2. TheDefinitionofT" The construction of an auc,,ented program T- for an arbitrary proarsi T conta'ning at most one cobe?i'n statement is accomplished by adding two l,inds of auxiliary variables to T . The firat type are ti?e' variables. like those in AorB' the second are "history" variables, used to record the values of program variables at ?ey poimts during program execution. 160 ?.`u.cfinjt?on: Rccall that program T of Theore: 6.19 has at most one cobe?in?statement T0 L0: resource rr??: cobe?in L1: T1 ?I.../I L?: TN coend Let 5 be any component of T Then rescurces(S) - ?r : 5 is a prop?r corponent of a withwhen state- ment for r?) var(S) - (variables or T) if 5 is not a proper conponent of T0 - (x: a does not appear on the left side of an asaign:ent stateaent in T. i 6 k), if 5 - T 1 1 - var(T?) tj ( L' r) if 5 is a proper rresources(5) component of Tk Note that var(s) is the set of variables which nay legally be used in 5 according to Definition 4.3. 6.21.Definition: The auxiliary variables to be added to the program T of Theoren. 6.19 are defined as follows. If T contains no parallel statement then T re?uires no auxiliary variables. If T co-tains the parallel atateaent T0 - L0: resource rrM: eobe?in L1: T1 /?.../? LN: TN coend the auxiliary variables are: 157 o ? ? ? < < ? ls? (true) bc?jn Atiee:-Rtin?e:--rltiee:r2tiT.e:Altin.e:-A2tir.e:--HBlti--He:--HB2ti:e:--HO; doneAl :=done?1 =0; (all variables havo the value 0) resource rl(dont:Al,rltine), r2(donell,r2ti=e): co?e-in A: (Altiee=A2tirc??tine?O) bt?in Al: with ri do be?in Altine:=l.max(Atire?rltifle); -Ati?c:=rltir.e:--HAltime; doneAl:-l end (A2tjrnc--O A Atime=Altirne>O) A2: with r2 do begin A2tirne:--l.;nsx(Atiine.r2ti:ne); Atir.e:=r2tir=e:=A2ti:e; B?irst:=?oneBl; end (A2t?rne=Atin.e>Altime>O) end (A2tin.c>Altine>O) I, (Bltirn?=82time=Bti?e=O) B (l2time>Blti?e>O) (processes A and B are svtaetric)= coend (Afirst?l V Bfjrst=l) end (Afirst-1 V Bfirst=1) I(rl) --H ((Altirne>O doneAl=l) (Altimc?B2tiee --H both l(r2) --H ((Dltirne>O ? doneBl-l) (A2time-lltimc both A (rlti;ne?Altine A rlti.--H.e>l2tire) A are 0) A (l2time??ltimeO Afirst--Hl)) A (r2tiee>lltjrr.e A r2tiae>A2ti?e) are 0) A (A2ti?e>Bltime>O ? Bfirat-l)) Figure 6.4. Informal Proof of (truc)AorB?(Afirst-l V Bfirat-l). 163 clear as the proof proceeds. For now, note that part of their useful ness stems fro the variety of assertions in which they can appear: L0initial x belongs to Proof?var(L,?) l)?truo Thus pre(s)[s] post(s)[s 8' a(S.ncxt(vslue(e),S)) - ?r(S.next(value(?r).S)) for reresources(s) Now 6' is an accept?ble local computation for process Tk which finishes S anJ x(s')--x[value(8')] V x Proof-var(S) (To check that 8' is an acceptable local coaputatlon it is only necessary to verify 2a-c of Jefinition 6.27 for the new element (5.next(value(8),S)) in the sequence.) For all reresources(S) ` ?r' is an acceptable resource co=pJ'ts tion which finishes 5 arA baa x!s,)?(vslue(Yr?)] V ?tProof-var(S) (To check this. it is only necessary to verify 3s-c of uefinition 6.29 for the new eleaent of the sequence.) 8ut this implies poat(S)[s')?true . givin pre(S)[s) ? y post(S)[s) or pre(S) -` post(S) 7. 5 is with r0 when B do ?l . S in process TIt a. Assume a is a program state with (pre(s) A 3 A r(r&)(s1.trao - 179 variable L?time but if 5 is a withwhcn statement, the `time" for 5 is Cl?max(L?time?r?tiae)) which will be assigned to Lktine as soon as the first statemcnt of the critical section is executed. 6.3S.Definition: Let a2 be a sequence of statements obtained by terging the statements of BB?, in a way which preserves the .th order of atate=ents within a single 8k and puts the I occurrence o+th of 5 fro:: Tk before the ? occurrence of 5' from T if timeCS,i.B?) < time(S'`?`0m? CSince time is nondecresaing within o+ these two requirements do not conflict.) We `must show e - a1Sa2 satisfies b and c from (.) . The following lemma is the basis of the proof. 6.36.Ler=a: a - a1Sa2 is a computation for T- with x!value(s0.e)]?x!value(6?)) V xvsrCT?) l))(s)?true Then fro post(Sk)(s] l