Está en la página 1de 14

EWD418

Guarded commands. non-determinacy and a calculus for the derivation of programs. by Edsger W.Dijkstra *)
*

) Author's address:

BURROUGHS Plataanstraat NUENEN 4565 5

The Netherlands. Abstract. for


So-called

''guarded commands" are introduced as a building block


r ep

alternative and

et itive constructs that allow non-deterministic


by

program components for which at least the activity evoked, but possibly even the final state, is not necessarily uniquely determined constructs, a calculus will be shown. Keywords. programming languages, sequencing primitives, program semantics, programming language semantics, non-determinacy, case-construction, repe tition, termination, correctness proof, derivation of programs, programming methodology. CR-category: 4.20, 4.22. the initial
of

state. For the formal derivation of programs expressed in terms

these

Guarded commands, non-determinacy and a calculus for the derivation of programs.

1.

Introduction.

In section 2, two statements. an alternative construct and itive construct will definition
of be

repet

introduced, together with an intuitive (mechanistic) The


basic building block statement for

their
"

semantics.
r

both of them
by

is the sb-called

gua d ed command", a

l it

pr

e fixed

a boolean

expression: only when this boolean expression is initially true, is the statement list eligible for execution. The potential non-determinacy allows us to map otherwise (trivially) different programs on the same program text, a circumstance that seems largely responsible for the fact that

EWD418

now

programs

can

b e derived in a more systematic manner than before.


3,

In section
nition

after a prelude defining the notation, a formal defi

of the semantics of the two constructs will be given, together with

two theorems for each of the constructs (without proof). In section 4, it will be shown, how upon the above a formal calculus for the derivation of programs can be founded. We would like to stress that we do not present an algorithm" for the derivation of programs: we have used the term "a calculus" for a formal discipline --a set of rules- such that, if applied successfully 1)
2)

it will have derived

correct progrem

it will tell us that we have reached such a goal.


propositional

(In choosing the term "calculus" we have been inspired by the integral

calculus" and the situation.)

calculus" where we have a very similar

2. Two statements made from guarded commands.


If the reader accepts "other statements" as indicating, say, assignment statements and procedure calls, we can give the relevant syntax in
BNF

[2]. In the following we have extended

BNF

with the convention

that the braces

"{ .

}" should be read

s:

"followed by zero or more

instances of the enclosed". <guarded command>::"' < guard>- <guarded list > <guard>::"'< boolean expression> <guarded list>::= <statement>{; <statement> } <guarded command set>::"' <guarded command> {0 <guarded commend>} <alternative construct>::= if < guarded command set>fi <repetitive construct>::= do < guarded commend set> <statement>
-

<alternative construct> I <repetitive construct> I "other statements"

The semicolons guarded list


is

in

the guarded list have the usual meaning: when the


execution

selected for

its statements

will

be executed

successively in the order from left to right; a guarded list will only be

EWD418 - 2

selected

for

execution in

state such that its guard is true,

Note that

a guarded command by itself is a statement:


guarded command

it is component of e

set f rom which statements can be constructed.

If the
they are arbitrarily

guarded command set consists of more than one

guarded command,
an

mutually

s epa rated

by the separator

"0"

our text is then

ordered enumeration of an unordered set,

i.e.

the order in which the guarded

commands of a set appear in our text is semantically irrelevant.

Our synta x gives two ways for constructing a statement out


guarded

of a

command set.

The alternative construct is written by enclosing


"if

it by the specie! brecket pair: of the guards is true, the

fi".

If inthe initial state none otherwise an arbitrary

program will abort,

guarded list with a true guard will be selected for execution.

Note.

If the empty guarded command set were allowed


"abort"

"if

fi"

would be

se man ti cally equivalent to

(End

of note.

)
fashion-

An example --illustrating the non-determinacy in a very modest

would be the program that for fixed


value of x

and

assigns to

the maximum

and

:
X

.!f.

2: 2:

y
x

m::

U
fi

m:= y

The repetitive construct is written down by enclosing a guarded

command set by the special bracket pair

".!!2.

..!:!."

Here

state

in

which none of the guards is true will not termination;

lead to

abortion but to proper

the complementary rule,

however,

is that it will only t er minat e when initilly or upon


one

in a state in which none

of the guards is true:

completed execution of a selected guarded list


a

or more guards guard

are

true,

new selection for execution of a gua rd ed list with a true and so on. When the repetitive construct has

will take

place,

terminated

properly,

we k now that all its guards are false.

If the empty guerded command set were allowed "do "skip"

..QQ" would

be

semantically equivalent to

(End

of note.

EWD418 - 3

An is the

example --showing the non-determinacy in somewhat


that assigns to the variables that

gr eat e r g lo ry

.I

--

program

q1, q2, q3 and q4 a permutation

of the values Q1, Q2, Q3

and

Q4,

such

q1 q2 <q3 <q4

Using
can

concurrent assignment statements fo r the sake of.convenience,

we

program

q1. q2, q3, q4 do q1 > q2 q1

:=

Q1, Q2 , Q3, Q4;


-

q2

q2, q1 q3, q2 q4, q3

0 q2 > q3 0 q3 > q4
.2

q2, q3 q3, q4

To conclude this s e c t io n
but al so the final s tat e is

we give a program where not only the computation

not necessarily uniquely determined. The program


for fixed value < n

should
fu

determine

such

that

(n > o)

and

a fixed

nct i on

f(i)

defined for
and N i :

0 <i

i <

k
>

will eventually satisfy : f (i) )

0 < k < n (Eventually k

n: f(k)

should be the place

of

maximum.)

k:c:
do j

0;

j:= 1;
n

f=

-if. f(j) <f(k)

j:= j + 1
-

D f(j) f(k)

k:: j; j:= j

Only permissible final states are possible


state is possible.

an d

each permissible final

3.

formal

definition of

t he semantics.

3.1. Notational prelude.


In

the

following sections

we shall use the

sym bols

and

to

deno t e (predicates defining)

boolean functions defined on all p oi nt s of we shall refer to them as "conditions",

the state space;

alternatively

satisfied by predicates
b

all

states for w hich

the boolean function


names
by
c

is and

true.
"F"

Two

special

that we denote by the reserved


T
f denotes

"T"

play a

special role:

t he condition by

tha t, the

definition,
on d it i on that

is satisfied

all states,

den o tes,

definition,

is satisfied

EWD418 - 4

by no state at all .

The way in which we use predi cat e s initial or final states)

(as a tool for def ining sets of

for the definition of the semantics of programming

language constructs has been directly inspired by Hoare difference introduces

[1 ],

the main

being

that we have tightened things up a bit:

while Hoare

sufficient p re-conditions such that the mechanisms will not

produce the wr o n g result ( bu t may fail to


n ec essary and that th e
sufficient --i.e. so-called

terminate),
"weakest"--

we shall introduce

pre-conditions such

mechnisms

are guaranteed to produce the right result.

More speci fically:

we shall use the notation R

"wp S,

R)"

where

denotes a statement list and

some condition on the state of the system, o f the system such

to denote the weakest pre-condition for the initial state that activation of
5

is guaranteed to lead to a properly terminating

activity leaving the system in a final state satisfying the post-ondition R

Such a "wp" --which

is

called "a predicate transformer",

because it

associates a pre-condition to any po st -con d i tion


the follow ing properties.

--

has,

by definition,

1)

For any

we have for all states

wp(5,

F)

:;::

( the

so-called "Law
S

of the Excluded

Miracle").
such that for all states

2)

for any

and any two post-conditions,

p => Cl
we have for all states wp( S,

P) =>

wp(S,

Q)
P and

3) states

For any

and any two post-conditions

we have for all

( wp ( S, P)
For any
5

and wp(S,

q))

wp S,
P

P
and

Q)
we have for all

4)
states

and any two post-conditions

(wp(S,

P)

or wp ( S,

Q))

=> wp(S ,

Q)

Together with the rules of propositional calculus and the semantic definitions to be given below, the above four properties take over the

EWD418 -

:role of the "rules of inference11 as introduced by Hoare [1 ].

We take the position that we know the semantics of sufficiently well wp(S, R)

m ec han ism

if

we know its

predic ate
R

transformer,

i.e.

can d eriv e

for any post-condition

Note.

This p os i t i o n is taken in full

acknowledgement

of the fact that in predicate

the case

of non-deterministic mechanisms, the knowledge of the not


give
a

transformer does

complete m

description:

for those initial s tates

that do not necessarily lead to e properly termi n ati ng activity, the


knowledge of the predicate tra nsfo r e r does not give us any information

about the final states in which the system might find i tse l f after proper termination. (End of note.)

Example 1.

The s emantic s of the empty statement,

denoted by R

"skip",

are

given by the d ef in ition that for any post-condition wp("skip", R)


=

we have

Example 2.
given by

The semantics of the assignment statement w p "x:= E'1, R

11x:= E"

are

R)
of th e predicate defining R
in wh i h each

in which

d e not es

c op y

o ccu rence
E xample 3.

of

the variable

"x"

is

replaced by

"(E)".

The semantics of the semicolon

";11 as c nca t nat ion operator

ere g iven by

wp("S1;

52", R)

wp(S1, wp(S21 R))

3.2.
In

The

alternative construct.
to define the seqantics

o r d er

of

the alternative construct we

define two abbreviations. Let


"If11

let

"BB11

denote .

\=

i _< n:

B )
i

then,

by definition

EWD418

wp(IF, R)
(The first term
n ot

(BB

arid

Ni:

:S i n:

B.

l.

=>wp(SL.,
l.

R))

"BB"

requires

that the al te r a tiv

construct as

such

will

lead to abortion on a cco unt


that

of all guards false, the second term

requires

e a ch

guarded list eligible for execution will lead to

an

ecceptable final state.) from this definition we can derive --by simple
substitutions--

Theorem 1

From
i < n: that => wp( IF,

Ct/i: 1 we
can c

(Q B.) =>
l.

wp(SL., R))
l

for all states

on clu de
and

(Q
Let
end of
sys t

BB)

R)

holds

for

all

state s

. "tIt

let "wdec(S, t) II den ote


5

d no e

e t some integer function,


th

defined on

the

state space,

e weakest

pre-condition such that activation


leavin g the

is guaranteed to lead to a
such that

properly terminating activity the value of l


value). In terms of

em in a final state very


From 1 _< i <n:
that

t is decreased by at
"wdec" we can

l eas t
mulate the

(compared to its i nitia similar

for

Theorem

2.

0Ji:
we can

(Q - B.) end
l

=>wdec(SL., t))
l.

for all states

conlude

(Q and BB)

=> wdec(Ir,

t)

holds for all states.

Nob

(which

can be skipped at first reading), for any

The relation between "wp"


regard

end "wdec" is as follows.

point X in state space we can

as an eq ua ion with be tmin(X).

t0

as

the

un

kn own .

Let its smallest solution for t 0

(Here we have

added the explicit dependence on

t he state the

X.)

Then

tmin(X)
t

can be interpreted tf themechanism 5

as

the lowest upper X

bound for

final

value of

is activated with

as initial state.

Then, by

definition,

wdec(S, (End of note.)

t)

(tmin(X)

t(X)

1)

(tmin(X)

<

t(X))

EWD418

3.3.
As is

The

reoetitive construct.

to

be expected,
SL1

the definition of the repetitive construct

0 ... 0

- SL
n

that Let
and

we denote b y

"DO"

is more complicated.

H0 (R) = for k >0:

Hk(R)

(R .!!!! BE) (wp(IF", Hk_1 (R))

E. H0(R))
fi
11

(where then,

"IF"

denotes the guarded command set enclosed by "if

by definition wp(DD, R)

(3k: k

0:

Hk(R))

(Intuitively,

Hk(R) can be interpreted as the weak est pre-condition guar

anteeing proper termination after at most leaving the system in a induction we can prove final
state

selections of a guarded list, R

satisfying

.}

Via mathematical

Theorem

3.

From

(P EB)
and

=> (wp(IF,

P)

and wdec(IF,

t))

for all states

P)=> (t
/

> o) ,

f o r Bll states

we can conclude that we have for all states


P => wp(D D

l!!:!

BB)

Note that the antecedent of Theorems 1 and 2.

Theorem 3 is of the form of the consequents of

Because wp(S, T

is the condition by definition satisfied

by all

states, for

is the weakest pre-condition g uara n t e ei ng

proper termination

This allows us to formulate an alternative theorem about the viz.

repetitive

construct,

Theorem 4.

From

(P

nd

BB)

=> wp(IF,

P)

for

all

states,

we can conclude that we have for all

states

(P In

and wp(DO,

T))

=>

wp(DD,

P and

BB)

connection with the above theorems

"P11 is called

"the invariant relation"

EWD418 - 8

and

"t"

is

called "the variant function".

4. Formal derivation of programs.

The f

ormal requirement of our program performing is


that fo r fixed
x

Hm:=

max ( x , y)"

--see above--

and

it establishes the relation

Now

the

Axiom of

A ssignm en t tells us
"m = x"

that

Hm:=

xH

is
"m:=

the is
x"

standard a way do
the

way of establishing the truth o f of establishing the truth of


job? the In order to investigete this,

for fixed x, which


R.

first term of

Will

we derive and simplify

x?:.y as

Taking this weakest pre-condition


if. x ? y

its g u ar d,

Theorem 1 tell

us that

m:=

x fi
it terminates succesfully.

will

produce the

correct result if
looking

The disad

vantage of this program is that BB


weakening guards. w BB means

T,

i.e. it might lead to abortion; which


might introduce new "m:= y" with

for

alternatives

The obvious alternative is the

assignment

the guard

p( m : = y", R)
"

y?:. x

thus

we

are led to

our pr x

ogra m

if
fi end by this time BB

m:= x m:= y

0 y ?:. x -

an

d therefore we
that th

have solved

the

problem. (In

the mean time


d efi e

we

have proved
R
con

maximum of two v lu
m

a es is always
has always a

n d,

viz. that

s id ere d

as equation for

solution.)
As an

example of the deriviation of a repetitive for the greatest common divisor


positive X

construct we shall

derive a program i.e.

of two positive numbers,

for fixed,

and

e have

to est bli

s h the

final

relation

EWD418

x = gcd(X, Y)
The formal machinery only gets in motion, once we have chosen our

invariant relation and our variant function. The program then gets the
structure "establish the relation P of P" & Suppose that we choose for the invariant relation P:
gcd X,
to

be kept invariant;

do "decrease t as long as possible under invariance

Y)

gcd(x, y) and

> 0 and

y > 0

a relation

thet

has the advantage of being easily established by x:=


X;

y:=

The most general "something" to


of the form
x,

be

done under invariance of P is

y:= E1, E2
such

and we are interested in a guard B (P B)


=>

that

wp("x, y := El, E2", P)


E1 > 0

= (gcd(X, Y) = gcd(E1, E2) and Because the guard must be a computable


not we

E2 > 0)

boolean expression and should

contain the
mu s

computation of that

gcd X,

Y)
E1

--for

that was the whol e


are so

problem-

t see to it

the

expressions

and E2

chosen,

that

the first term


gcd(X, Y) is implied by P , which
is
:

gcd(E1,
if

E2

true

gdc(x, y) =

gcd E1,

E2)

In other words we are invited to massage the value pair a fashion that their gcd

y) in such
is

is not changed. Because --and this

the place

where to mobilize our mathematical knowledge about the gcd-function-gcd(x, y)


a
:

gcd(x

y, y)

o ib l guarded list would be


ss e

x:= x
Deriving

- y

EWD418 - 1

wp{"x:= x - y", and omitting

R)

(gcd(X, Y)

gcd{x

y, y) and

x -

y > 0 E..!J.9. y > 0)

ell terms of the conjunction


><

implied

by

we find the guard

>y
of th P is concerned.
fu Besides

as far as the consequences

inv

a r i ance
of

that

we

must require

guaranteed decrease

e variant

nction t . Let us investigate the

of the choice

From

wp("x:=
wp{"x:=

y",

- "", J

t 5 t ) = 0 x + y t0)

= (x < t0)

we conclude that

tmin ,.,

therefore

wdec(":=

y", t)

= (x

<

+ y)

= (y > 0)

The requirement of monotonic decrease restriction by


P and

of

t
- y",

imposes no further

of

the guard because wdec("x:= x


com

t)

is fully

implied

we

at our first effort x:= X; y==

Y;
Xl"' X

.Q.Q.

> y -

- y .!!

Alas,

this single guerd is insufficient:

from

8B

we

ere not allowed to c o ncl de


manner,

x =

gcd(X, Y).
wi l

In a

completely analogous y>x

the

alternative y:= y
is

- x

l require as its guard

and

our

next effort

x -

X t

y: = Y '
x -

do
'

>y
X

)( -

y
X

0
9.

y>

y- y
-

Now the job is done, be ca us e


and

with this last p o g r

am

non

BB

= y)

(P x

= y)

=> (x = gcd(X, Y)
t x

because
the

gdc(x, x) = x

N ote. The
gcd

choice of symmetric

+2y

nd

knowledge of the fact that


the program

the

is

function could have led to

EWD418- 11

x:= X; y:= Y; do
X

>y

x::

'j
X

0
od The swa p
"x, y
:

y >X

- X,

y := y,

y, x"

can nev er destroy

P :

the

g u ar d of the last
t

guarded list is fully caused by t he decreased.

requirement that

is effectively

In

bo th cases the fi nal lists


that

game has been t o f i nd a large enough set of the disjunction of their guards,

su c h

guarded

BE

was suffi

ciently weak: in the case of the alternative construct the purpose is avoiding abortion, in the cas e of the re p e tit iv e
ge ttin g

construct the goal is is strong enough to

BB

wea k enough such that


A

and BB

im ply the desired pos t-c ondition

5.
The
tr i gge red

C onc l ud ing remarks.

research,

t he

outcome of

which is

reported in this o r tic le , was

by the

ob servat ion that Euclid's Algo r i t hm could lso be regrded

as synchronizing. the two cyclic


in such a way that the

proce sse s ".2.

x:= x - y od" and "&!2. y:= y-x od'

re lation

x > 0 y >0

would be kept in varian tly that the


formal

true.

It

was

only

after this observation that we

saw

tec hn iq ues we had already developed for the derivation of the


conditions that
ensure

synchronizing

the harmonious co-operation


in

of

(cyclic) sequential
opP.rating

processes, su ch as can be identified


systems , could be transferred lock,
of

the total activity of

stock and barrel to the development

s eque n tial

programs as shown in this article.

The main difference is


a

t hat while for sequential programs the situation "all guards false" is

desirable goal --for

it

means

termination of a repetitive construct--.,

one tries to avoid it in operating

sys tems --for there it means deadlock.


was my p in

The second reason to pursue these investigations


desire to get a better appreciation
--among other

ersona l

things

o rd e r to be

able

to

evaluate how realistic some claims towards "automatic programming"


w h ic h part of

were--

the p rogrammi ng of it s e ems

activjty

can

be regarded as formal

routine and which.part


design of

to require "invention". While the

an a lt erna t ive construct n ow seems to be a reasonably strai g ht-

EYJD418

12

forward activity, that of a repetitive construct requires what I "the invention" of an invariant relation and a variant function. the main va lue of the calculus shown in

re gard as For me ,

section 4 is that it has strenght

ened my skepticism about some of the claims or go;;ls of 11automatic pro gramming11; me presenting this calculus should not be interpreted as me it just gives

sugges ting that all programs should be developed that way: us another handle.

The calculus does,

however,

explain my preference for the ax iomatic

definition of programming lan gua ge semantics via predicate transformers abo ve

other defi nition techniques: thP. defini tion via predicate transforers

s eems to lend itself most radily to being forged into a tool for the goal directed activ i ty of program composition.

Finally I would like to say a word or two about the role of tential nan-determinacy.

the po

I quote in this connection C.A.R.Hoare: 11A system

which perm its user programs to become non-deterministic pres en ts dreadful problems to the maintenance engineer: granted. ware.) " it is nat a
" facility "

to be lightly

( This

is particularly true in the absence of self-checking hard

l mysel f had to overcome a considerable mental resista nce before I It

found myself willing to consider non-deteinistic programs seriously. is, however, fair to say that I could not have discovered the calculus

shown before having take n that hurdle and I leave it to the environment whether the non-determinacy is eventua lly resolved by human in terventi on or mechanic ally , in a reproducible manner or not. (It is only in an envi

ronment in which all programs should be determini stic, where non-reproducible behaviour is interpreted as machin e malfunctioning: I can easily think of

an environment in which non-reproducible user program behaviour is quite


naturally and almost always
c o rrec tly

taken as an indication that the user

in ques tion has written a non-deterministic p rogram !

Acknowledgements.

In the irst place my acknowledgements are due to the memb ers of the IFIP Working Group W.G.2.3
a

on

" Progrcrnming

Methodology":

it was,

as

matter of fact,

during the

Blanchland

meeting of this Working Group in

October

1973 tha t the guarded

commands were both born and shown to the

EWD418 - 13

public. In connection with


Hoare,

this

effort

its members R.M.Burstall, C.A.R.

J.J.Horning, J.C.Reynolds, D.T.Ross, G.Seegm6ller, N.Wirth and M.


another.

Woodger deserve my special thanks. Besides them, W.H.J.Feijen, D.E.Knuth, M.Rem and C.S.Scholten have been directly helpful in one way or

I should

elso thank

the various audiences --in Albuquerque (courtesy NSF),


one

in San Diego and Luxembourg (courtesy Burroughs Corporation)-- that have played their role of critical sounding board beyond what to hope. is entitled

(1]

Hoare,

C.A.R., An Axiomatic Basis for Computer Programming, Comm.ACM 12

( Oct.
[2]

1969) 576- 583.

Naur, Peter, (Ed.) Report on the Algorithmic Language ALGOL 60,


3

Comm.ACM

(Hay 1960)

299- 314

26th

June

1974

prof.dr.Edsger Burroughs

W.Dijkstra

NUENEN

Research fellow

También podría gustarte