Вы находитесь на странице: 1из 95

Chap.

2 I Computer Hardware

2.2.1 Core
Ferrite core, a type of nonvolatilestaticRAM, is a bistabledevice that replaced
memoriesbasedon vacuumtubesin the early 1950s.Core memory consistsof a
doughnut-shaped magnet through which a thin wire called a drive line passes.
Perhapsas a child you built a simpleelectromagnet with a 9-volt battery,nail, and
wire. The operating principle of core memory is related.
In the core memory, the direction of flow of current through the drive line
establisheseither a clockwise or counterclockwisemagnetic flux through the
doughnut correspondingto either a logic 1 or a logic 0. A secondwire called the
senseline is usedto "read" the memory (seeFigure2.8).When a currentis passed
through the drive line, a pulse is generated(or not) in the senseline dependingon
the orientation of the masnetic flux.

Senseline

Drive line
Drive Figure 2.8 Core memory element.

Core memories are slow (l0-microsecond access)and bulky, and consume


lots of power, but they do have one advantage-they cannot be upset by
electrostaticdischargeor by a chargedparticle in space[95]. This considerationis
important in the reliability of space-borneand military real-time systems.

2.2.2 SemiconductorMemories
RAM devices can be constructedfrom semiconductormaterials in a variety of
ways. The semiconductormaterial is used to form a bistable logic device called
aflip-flop. The excitation for an RS type flip-flop.is given in Table 2.6. The flip-
flop has two inputs: the set line, S, and the res€rline, R The next stateof the flip-
flop (shown in the table) is determinedby the input lines and its current state,Q.
The x iepresentsa "don't care" state-that is, it should be unachievable.
Sec.2.2 I Memories 45

TABLE 2.6 RS Flip-Flop Excitation Table

RS Input
Current
stare (Q) 0t 10 ll

0 l 0 x
I 1 0 x
Next State

The flip-flops are so configured as to form a single bit of storage, an


example of which is shown in Figure 2.9. The basic one-bit cells are then
configured in an array as in Figure 2.10 to form the memory store.
Both static and dynamic RAM can be constructedfrom several types of
semiconductormaterials and approaches.Typically, dynamic memories require
less power and are denserthan static ones; hoivever, they are much slower.
The requiied refresh of the dynamic RAM is accomplishedby accessing
each row in memory by setting the RAS (row addressstrobe) signal without the
need to activate the CAS (column addressstrobe) signals.This is called a RAS

Selectline

Read/writeline
(a)

Selectline

Inputline OuFutline

Read/wrile

(b)

Figurc 2.9 Logic diagram for single bit of memory (a) and block diagram
representation (b).
46 Chap,Z I Computer Hardware

Inputlines

Decoder

Dm-t

Figure 2.10 The n X m memory array using single-bit block representation.

only refresh.The RAM refreshcan occur at a regularrate (e.g.,4 milliseconds)


or in one burst. A significant amount of bus activity can be held off during the
dynamic refresh,and this must be taken into accountwhen calculating instruction
execution time (and hence system performance).When a memory accessmust
wait for a DRAM refresh to be completed, we call this cycle stealing. If burst
mode is used to refresh the DRAM, then the timing of critical regions may be
adversely affected when the entire rnemory is refreshed simultaneously.
Depending on the materials used and the configuration, access times of 15
nanoseconds(15 billionths of a second) or better can be obtained for static
semiconductorRAM.

2.2.3FusibleLink
Fusiblelink ROMs are a type of nonvolatile memory used to store programs.
These memories are sometimes generically called programmable read-only
memories (PROMs), or programmabte logic arays (PLAs), and consist of an
Sec.2.2 I Memories 47

lf fused,each
crossinglookslike:

01 oz

Figure 2.11 The n-input m- outilut fusible-link PROM.

array of paths to ground calledfusible links. During programming thesefuses are


.,blown" to representeither ls or 0s thus embeddingthe program into the memory.
Sincefusible-link memoriescannotbe reprogrammed,they cannOtbe accidentally
altered. They are very fast and can achieve access times of around 50
nanoseconds. A fusible link PROM is depictedin Figure 2.11'

2.2.4UVROM
Ultraviolet read-only memory ruVROM) is a type of-nonvolatile PROM with the
special feature that it can be reprogrammed a limited number of times' For
reprogramming,the memory is first erasedby exposingthe chip tb high-intensity
ultraviolet light. UVROM is typically used for the storageof program and fixed
constants.UVROMs have accesstimes similar to those of fusible-link PROMs'

2.2.5EEPROM
Electronically erasableprogrammable read-only memory GEPROM) is another
type of nonvolatile PROM, with the special feature that it can be reprogrammed.
EEPROMs are used for long-term storage of variable information. These
4t Chap. 2 I Computer Hardware

memories are erasedby toggling conrrol signals on the chip, which can be
accomplishedunder program control. For example,the high scoreinformation on
an arcade-typevideo game is storedin EEPROM. Thesememoriesare slower
than other types of PRoMs (50-200 ns accesstimes) and have higher power
requirements.

2.2.6FlashMemory
A new memory technology for programmableRoMs has recentry emerged.This
technology, called flash memor), uses a single transistor per bit, whereas
EEPROM uses two transistorsper bit. Hence, flash is more cost-effective
and
densethenEEPROM.Accesstimes for flash are quite fasf, 20 to 30 nanoseconds.
The main disadvantageof flash is that it can be written to and erased about
100'000times, whereasEEPROM is at I million. This technologyis finding its
way into commerical electronics applications, but it is expected to appear
increasinglyin embeddedapplicationssuch as avionics.

2.3 INPUTANDOUTPUT

Input and output of data to a computersystemis accomplishedthrough one


of
three differenr methods:programmedvo, memory-.upp.o vo, or oMa
loirect
memory address).Each methodhas advantagesand disadvantageswith respect
to
real-time performance,cost, and easeof implementation.

2.3.1 Programmedl/O
In programmed VO, special instructions in the CPU instruction set are used
to
transfer data to and from the CPU. An IN instruction will transfer data from
a
specifiedVO device into a specifiedCPU register.An OUT instruction will output
from a register to some UO device. Normally, the identity of the operative
CiU
register is embeddedin the instruction code. Boih the IN and OUT instructions
require the efforts of the CPU and thus cost time that could impact real-time
performance.

I EXAMPLE2.10
A comPutersystemis used to control the speedof a motor. An output port is
connectedto the motor,
and.asigned'integeris written to the port to set the motor speed.The computer
is configured so that
when an OUT instruction is executed,the contentsofregister I are placed on
the data bus and sent
49
I Input and OutPut

program
to I/O port at the addresscontained in register 2. The following code fragment allows the
to set the motor sPeed.

LOAD Rl, speed motor speed into register I


LOAD R2, motoraddress addressof motor control into register 2
OUT output from register 1 to the memory-mapped I/O
port addresscontained in register 2 |

l/O
2.3.2 Memory-MaPPed
Memory-mapped I/O provides a dala transfer mechanism that is convenient
becauseit does not require the use of special CPU VO instructions, and has the
additional advantage that the CPU and other devices can share memory. ln
memory-mappedI/O ceftain designatedlocations of memory appear as virtual
input/output ports' (See Fig:ure2.12.)

Output

Wul
Output

VO circuitry.
Figure 2.12 Memory-mapped

T EXAMPLE 2.11
themotbrspeedcontroldiscussed
Consider via
in Example2.10.If it wereto be implemented
memory-mapped
VO, it mightlook like the following:

LOAD R1, sPeed motor speedinto register I


STORE R1, motoraddress storeto addressof motor confrol

Note that a memorylocationwould haveto be tied to themotorcontrolvia Ir(J cardcircuitry. I


50 Chap. 2 I Computer Hardware

I EXAMPLE
2.12
In many computersystems,the video display usesmemory-mappedI/O. The screenis a 24 row by
80 column anay (a total of 1920characters). Each screencell is associatedwith a specificlocation
in memory. To update the screen,charactersare stored to the addressassignedto that cell on the
screen.Although actualmemory doesnot exist at this location,the memory circuitry decodesthis
addressinto an existingoutput port and initiatesa DST or data strobetransmitsignalto initiate the
data transfer to the video disolav card t

Reading from a memory-mappedlocation involves executing a LOAD


instructionon a pseudomemorylocation connectedto an input device.
It should be noted that the overhead incurred in decoding the memory-
mappedread or write instructionand the responsetime of the device involved
must be consistentwith the normal responsetime of actual memory. If the
instruction decode and response time is faster than actual memory, then no
problemexists.If this time is slowerthanactualmemory,thenthe overall memory
responsetime must be adjustedto conform throughthe use of extra clock cycles
called wait states.
Memory-mappedI/O locations are not usually input and output simultane-
ously. Thus, if a, record of what has been output to or input from a memory-
mappedlocationis needed,a RAM imageof it shouldbe kept. This mirror image
should be updatedto reflect the current"contents"(rnostrecentoutput or input)
of the memory-mappedlocation.

2.3.3DMA
ln direct memory access(DMA), accessto the computer'smemory is given to
other devicesin the system without CPU intervention.That is, information is
depositeddirectly into main memoryby the externaldevice.Here,the cooperation
of a devicecalleda DMA control/eris required.BecauseCPU participationis not
required, data transfer is fast.
The DMA controller is responsiblefor assuring that only one device can
placedataon the bus at any one time, a roie calledbusarbitation.If two or more
devicesattemptto gain control of the bus simultaneously, bus contentionis said
to occur.When a device alreadyhas control of the bus and anotherobtains access,
this undesirableoccurrenceis called a collision.
The DMA controller preventscollisions by requiring each device to issue a
DMA request signal (DMARO that will be acknowledged with a DMA
acknowledge signal (DMACK). Until the DMACK signal is given to the
requesting device, its connection to the main bus remains in a tri-state
condition-that is, a high-impedancestatethat, in effect, disconnectsthe device.
Any device that is tri-statedcannotaffect the data on the memory data lines. Once
the DMACK is given to the requesting device, i$ memory bus lines become
active, and data transfer occurs as with the CPU.
The CPU is preventedfrom performing a datatransferduring DMA through
the use'of a signal called a bus grant. Until the bus grant signal is givenby the
I Input andOutput 51

DMA
controller

Figure 2.13 DMA controller hardware.

DMA controller, the normal CPU data transfer processescannot proceed.At this
point, the CPU is effectively suspendeduntil it receivesthe bus grant, or until it
gives up (after somepredeterminedtime) and issuesa bus time-out signal. See
Figure 2.13 for a block diagramof typical DMA=controllerhardwareand Figure
2.I4 for the timing sequence.
Becauseof its speed,DMA is the best method for input and output for real-
time systems.Usually a specialareaof memory is designatedfor DMA memory.

DMARO

Time

Figure 2.14 DMA transfertiming diagram.


Chap.2 I Computer Hardware

2.3.4lnterruptDrivenlio
Some persons may comment that there is a fourth type of I/O in addition to
program I/O, memory-mappedI/O, and DMA-that is, intemrpt driven I/O.
However, intemrpt driven I/O is simply a variation of one of the other three in
which an intemrpt is used to signal that an I/O transferhas completedor needsto
be initiated via one of the three mechanisms.

2.4 OTHERDEVICES

Real-time computer systemsusually contain other devices that dependon the


application,but must interfaceto the real-timesoftware.In this sectionwe discuss
some of thesedevicesand their impact on real-timesystems.

2.4.1MUXTransceivers
Transmit/receive hybrid devices,sometimescalled transceivers,provide commu-
nication servicesto other devicesjoined by a common bus.
If the bus is serialin nature,or if the numberof lines on the bus is lessthan
thoseintemal to the device,then a devicecalleda multiplexeror MUX is needed.
The MUX card usually interfaceswith the CPU through DMA hardware and is
responsible for ensuring that all transmitted and received data conform to an
appropriateprotocol. This processincludes parallel to serial conversion and vice
versawith shift registersand other circuitry (seeFigure 2.15). For example,the
well-known universalasynchronousrelay terminal (UART) is used for parallel-
to-serial bus interfaces and is seenin many commercial applications.
Another example of such a bus structureis representedby the Mil-Std-
15538 bus standardthat specifies(besideshardwareguidelines)transmissionand
receiptprotocols.The 15538 standardis arrangedso that one module on the bus

Transmit
register

hybrid.
Figure 2.15 A typicaltransmiVreceive
Sec. 2.4 I Other Devices 5J

Figure 2.16 Mil-std-1553B bus arrangement.

acts as a bus controller and the others respond to its commands.This type of
configuration is common in many commercial networks and computer sub-
systems,and is illustratedin Figure 2.16. Another exampleof MUX transceiver
commonly in use is the IEEE488 parallel configuration.

2.4.2A/D Circuitry
Analog-to-digital conversion or A/D circuitry converts continuous (analog)
signals into discrete (digital) ones. Circuitry like this can be used to sample
temperature,sound,pressure,and so on, and usesa variety of schemesto perform
the conversion.The methodology involved is beyond the scopeof this book, but
interestedreaderscan refer to [138].
The output of A/D circuitry is a discrete version of the signal being
monitored, which changesat somerate. This information can be passedon to the
real-time computer system using any of the three data transfer methods, but in
each case the A/D circuitry makes available an n-bit number that representsa
discrete version of the signal. The quantized version of the continuous value is
usually handled as a scaled number (see Chapter 10).
The key factor in the serviceof A/D circuitry isthe sampling rate.In order to
convert an analogsignal into a digital form without loss of information, samplesof
the analogsignalmust be takenat twice the rateof the highestfrequencycomponent
of the signal (theNyquist rate).Thus, a signalat 60 Hz must be sampledat 120times
per second.This implies that softwaretasksservingA7'Dcircuitry must run at least
at the samerate,or risk losing information. This considerationis an inherentpart of
the designprocessfor the schedulingof tasks.

2.4.3D/ACircuitry
Digilal-to-:analog conversion or D/A circuitry performs the inverse function bf
A/D circuitry; that is, it converts a discrete quantity to a continuous one. D/A
devices are used to allow the computer to output analog voltages based on the
digital version stored intemally. Communication with D/A circuitry uses one of
the three methods discussed.With D/A conversion, the issuesare related to the
scalednumbers discussedin Chapter 10.
Chap.2 I ComputerHardware

2.4.4 InterruptControllers
Not all CPUs have the builrin ability to prioritize and handle multiple interrupts.
An extemal intemrpt-controller device can be usedto enablea CPU with a single-
interrupt input to handle interrupts from several sources.These devices provide
the ability to prioritize and mask intemrpts of different priority levels. The
circuitry on boardthese.devices is quite similar to that usedby processorswhich
can handle multiple interrupts, including mask circuitry, intemrpt registers, and
the like (seeFigure 2.17).
When configuredas in Figure 2.18, a single-intemtptCPU in conjunction
with an interrupt controller can handle multiple interrupts.

To CPU

Data
bus-
buffer

Interrupt0
Interrupt1

Interrupt(n - 1)

Interrupt
inputs

Figure 2.17 Block diagram of a programmable intemrpt controller.

Reset
Interrupt
signal 1 Interrupt_
Programmable
interrupt CPU
controller /,-u39!-r\
\-------tl
,4yector.J\

Figure 2.18 Handlingmultiple interruptswith an interrupthandler.

t_
Sec. 2.4 I Other Devices 55

The following scenario illustrates the complexity of writing intemrpt


handler software, and points out a subtle problem that can arise.

2.13
I EXAMPLE
An intemrpt handler executesupon receipt of a certain interrupt signal indicated by a logic l. The
first instruction of the routine is to clear the interrupt by strobing bit 0 of the interrupt clear signal.
Here, intclr is a memory-mapped location whose least significant bit is connected with the clear
interrupt signal. Successivelystoring 0, 1, and 0 servesto strobe bit 0.
Although the interrupt controller automatically disables other interrupts upon receipt of an
interrupt, we immediately reenable them to detect spurious ones. The following code fragment
illustrates this process for a 2-addressarchitecture:

LOAD R1, O
LOAD R2,I
S T O R ER 1 , l n t c l r set clear interrupt signal low
S T O R ER 2 , i n t c l r set clear interrupt signal high
S T O R ER 1 , i n t c l r set clear intemrpt signal low
EPI enable intemrpt

The timing sequenceis illustrated in Figure 2.19. Note, however, that a problem could occur if the
interrupt is cleared too quickly. Supposethat the clear, LOAD, and STORE instructions take 0.75
microsecond, but the interrupt pulse is 4 microseconds long. If the clear interrupt instructioh is
executedimmediately upon receipt of the intemrpt, a total of 3 microsecondswill elapse.Since the
interrupt signal is still present,when intemrpts are enabled,a spurious interrupt will be caused.This
problem is insidious becausemost of the time, software and hardware delays hold off the intemrpt
handler routine until long after the intemrpt signal has latched and gone away. It often manifests
itself when the CPU has been replaced by a faster one'

Interrupt Interrupt
initiated initiated

Interrupt
signal

Clear
interrupt

Enableinterrupt

Time in microseconds

Figure 2.19 Timing sequencefor intemrpt handling.

I
56 Chap.2 I Computer Hardware

2.4.5WatchdogTimer
In many computer systems, the CPU or other devices are equipped with a
counting register, which is incrementedat some rate but must be cleared before
the register overflows. This type of hardwareis called a watchdog timer orwDT
(see Figure 2.20). Watchdog timers are used to ensure that certain devices are
servicedat regularintervalsand that the CPU continuesto function.For example,

r- T-l l-l

Figure 2.20 Watchdog timer configuration.

if the cPU is required to reset a watchdog timer every second and a wDT
overflow occurs,then eitherthe CPU hasmalfunctionedor the 1-secondcycle has
time-overloaded. Watchdogtimers are useful in detectingdeadlocks,Incidentally,
resettingthe timer is sometimescalled "petting the watchdog."

2.5 EXERCISES
1. Discuss why it is unlikely that there exists an "n-address" machine where n > 3.
2. Update Tables 2.2, 2.3, 2.4, and,2.5 for the logical instructions AND, OR, XOR, and
NOT.
3. Change Tables 2.2, 2.3, 2.4, and 2.5 to reflect how rhe CCR might be updated by the
arithmetic instructions already described,and the logical instructions you defined in the
previousexercise.
4. Write a program that selects the largest of a list of l0 numbers stored consecutively at
symbolic location list, and storesthe result in symbolic location max.Do this tising the
generic assembly language for a
(a) O-addressmachine
(b) l-addressmachine
(c) 2-addressmachine
(d) 3-addressmachine
For the 0-addresscode draw the binary parsetree, and also show the contentsof the stack
after each instruction.
5. Write a program that sums the integers in five consecutivememory locations starting at
symbolic location x. Store the result in symbolic location y. Do this using the generic
assembly language for a
(a) 0-addressmachine
(b) l-address machine
(c) 2-addressmachine
(d) 3-addressmachine
For the O-addresscode draw the binary parsetree, and also show the contentsof the stack
after each instruction.
I Exercises

6. Write a program that sums the integers in n consecutive memory iocations starting at
symbolic location-r. (n is storedin symboiic location num.) Storethe result in symbolic
location y. Do this using the genericassemblylanguagefor a
(a) O-addressmachine
(b) 1-addressmachine
(c) 2-addressmachine
(d) 3-addressmachine
For the O-address codedraw the binary parsetree,and also show the contentsofthe stack
after eachinstructton.
7. Write a program that performsthe calculation
tt-'l-+yt
x'+ y'
-r, y, and z are symbolic locations.x and y are real numbers.Do this using the generic
assemblylanguagefor a
(a) O-address machine
(b) 1-addressmachine
(c) 2-addressmachine
(d) 3-addressmachine
For the 0-addresscodedraw the binary parsetree,and also show the contentsofthe stack
after each instruction.
8. Write a program that performs the calculatron
s=- 14x3-y2+8xy
-r, y, anclz are symbolic locations.Do this using the genericassemblylanguagefor a
(a) 0-addressmachine
(b) 1-addressmachine
(c) 2-addressmachine
(d) 3-addressmachine
For the 0-addresscode draw the binary parseftee, and also show the contentsof the stack
after each instn-rction.
9. Write a program that performs the convolution of two discrete signals.The first signal is
storedin l0 consecutivememory locationsstartingwith symboliclocationx. The second
signal is storedin 10 consecutivememory locationsstartingwith the syrnboliclocation
y. The resultant signal is to be stored in consecutivelocations starting with the symbolic
location z. The convolution sum is given by
l0
t(t) = y(r - i)
,\,;(i)
Do this using the generic assembly language for a
(a) O-address machine
ft) l-addressmachine
(c) 2-addressmachine
(d) 3-addressmachine
For the 0-addresscode draw the binary parseffee, and also show the contentsof the stack
after each instruction. You may use the proglam of the previous problem as a
subroutine.
10. Write a bubble sort routine in assembly language for a
(a) 2-addressmachine
(b) 3-addressmachine
(Ilinr. Assume the instruction EXCH is available.This instruction exchangesthe contents
of the two operandsgiven.)
Chap. 2 I Computer Hardware

11. The instruction set of a certain processor does not have the JLE, JLI, JGE, and JGT
instructions. Assume the processor does have all other arithmetic instructions and the
JNE and JUA instructions. Implement the missing instructions for the generic assembly
language in a
- (a) O-addressmachine
(b) 1-addressmachine
(c) 2-addressmachine
(d) 3-addressmachine
(Hint: Yo]u will have to load registers or the stack with the two comparands and the
conditional transfer locations.)
12. Why is DMA controller accessto main memory in most systemsgiven higher priority
than CPU accessto main memory?
L3. Discuss the relative advantages/disadvantages of DMA, program IiO, and memory-
mapped data transfers as they pertain to real-time systems.
14. Based on your understanding of computer architecture, rilnk the assembly language
instructions in Table 2.3 from fast (l) to slow (10) for a machine with which you are
familiar. Assume all instructions use direct addressingand that the memory accesstimes
are fixed. Also assume all instructions starting with a "J" have the same execution
time.
15. Describe the relationship between the main processorand coprocessorin a system with
which you are familiar. If you are not familiar with any, irse the Intel 8086
microprocessorand its associatedcoprocessor,the 8087.
16. What special problems do pipelined architecturespose for reahime system designers?
Are they any different for non-real-time systems?
17. Redraw Figure 2.8 using a ferrite core memory instead of an RS flip-flop.
18. Compareand contrastthe different memory technologiesdiscussedin this chapteras they
pertain to real{ime systems.
19. Should the instruction following the "TEST" instruction be interruptable? If so, what
must the implicit BRANCH instruction (intemtpt) do?
20. It is common practice for programmersto create continuous test and loop code in order
to poll I/O devices or wait for interrupts to occur. Someprocessorsprovide an instruction
(wait) that allows the processorto hibemate until an interrupt occurs. Why is this second
form more efficient and desirable?
Language
lssues

KEY POINTS OF THE CHAPTER

L Generally, more abstraction leads to degradation of real-time


performance.
2. certain languagefeatures,such as unboundedrecursion,while loops, and
intemrpt handlers,have nondeterministicrun-time performance.
3 . certain languagefeaturessuch as pass-by-valueparameterpassinghave
desirablereal-time performanceimpact.
4. It is important to understandthe compiler in use and how it generates
code frorn a particular usage of the language.

In this chapter we identify language features and their impact on real-time


programming. In addition, we addressthe issuesinvolvedrin understandinghow
compilers generateassemblycode basedon the highJevel languageinput. Finally,
we survey some of the languagescommonly used for real-time systemson the
basis of the criteria previously developed.
we discuss only those languages that are most often used in real-time
systems.
when I first wrote this chapter,I included those languagesthat were being
used'chiefly to write embeddedreal-time systems (Ada, Fortran, c, Assembl!
language).Since then, c++ and visual Basic have become very hot commercial
programming languages,and the new object-orientedAda 95 has been released.
Furthermore, since writing this chapter significant research has occurred in
programming languages that are suitable for real-time. Interested readers are
refened to [156].
60 ChaP.3 I LanguageIssues

The United States Army's former principal language, FORTRAN, is


includedin this chapterbecauseit is still taughtat universitiesand is usedin many
real-time applications.In addition, the U.S. Army, Air Force, and Navy are
currently required to procure software written in the Department of Defense's
languagestandard,Ada. Conspicuouslyabsentfrom the discussionare CMS-2 (a
languageonce favored by the U.S. Navy) and JOVIAL (a languagehistorically
usedby the U.S. Air Force),becausethey have beendisplaced,for the most part,
by Ada.
Next, Pascaland C arediscussedbecausethey are widely taughtand usedin
many real-time applications.BASIC is included for comparisonpurposesonly.
The chapteris roundedout with a look at assemblylanguageand its role in real-
time systems"
We do not discussthe useof applicativelanguagessuchasLISP in real-time.
Although the importance of such languagesin the construction, for example, of
real-time artificial intelligenceor expert systemsis undeniable,researchin this
areahas been limited thus far (for example, see[4]). The reader is referred to the
Bibliographyfor additionalreadingon suchreal-timelanguagesas occam2I2ll,
CSML [25], or ESTEREL U8].
Although there are also several specialized languages for real-time,
discussionhere of these are deferred. However, it should be statedthat real-time
languagesseekto support expressionand analysisof temporal behavior in one of
three ways:

r Elimination of constructsthat have indeterminateexecution times, such


as infinite loops (e.g.,Real-TimeEuclid t1571).
r Extensionof existing languages(e.g.,real-time C).
r Construction of languagesjointly with the operating system (e.g',
MARUTItl03l).

FEATURES
3.1 LANGUAGE

Several language features are desirable in a real-time language.These include


versatile parameter passing mechanisms, strong typing, exception handling,
interrupt types, and modularity. Many of these features are desirable for well-
written non-real-time programs. We discuss these and other important language
features,with emphasison their impact on real-time performance.

3.1.1 ParameterPassing
Methods of parameterpassing include the use of global variables, call-by-value,
and call-by-reference.Not every parameter-passing mechanismis supportedby all
languages, and each has its merits and problems'
I LanguageFeatures 61

3.1.1.1 Call-By-Value In call-by-value parameterpassing,the value of


the actual parameter(the namedvariablepassedto the procedure)is copiedinto
the called procedure'sformal parameter (the dummy variable used in the
definition of the procedure). Since the procedure manipulates the formal
parameter,the actual parameteris not alteredby execution of the procedure.This
type of methodologyworks well when either a test is being performedon dataor
the data are to be used as the input to some mathematicalfunction. Languages
such as Pascal,C, and Ada supportthis parameter-passing scheme.

I EXAMPLE
3.1
In this C code fragment,function "abs" will return the absolutevalue of any integervalue passed
to it without changingthe value of the integer itself. In this case call-by-valueis the preferred
method.

int abs(int x)
{
rf (x < 0 )
raf rrrn I -Y l

^ t ^ ^

return (x) ;
I

Parametersthat are passedusing call-by-valueare typically copied onto a


stack at run-time. at considerableexecutiontime cost.

3.1.1.2 Call-by-Reference In call-by-referenceor call-by-address,the


addressof the parameteris passedby the calling routine to the called procedure
so that it can be altered there. Execution of a procedureusing call-by-reference
parametersusually takes longer than when all the pa.rametersare passedusing
call.-by-value, since indirect instructions are needed for any calculations
involving the variables passed.Most versions of FORTRAN are strictly call-by-
reference,whereasPascal and Ada provide for this mode in addition to call-by-
value. C supportscall-by-value,but call-by-referencecan be simulatedusing
pointer types.
Call-by-reference can present problems in some languages like
FORTRAN.

I EXAMPLE3.2
In this FORTRAN code fragment subroutine "AVERAGE" is accidentally being called with the
number 4 as theJirst parameter(something the'compiler would not complain about). In order to pass
the addressof the number 4 to the subroutine, many compilers will create a hidden, anonymous,
variable and pass its addressto the subroutine.Unfortunately, the contents of this memory location
will be altered by the subroutine,causing problems for any other subroutinesusing the number 4 as
a Darameter.
62 Chap. 3 I LanguageIssues

SUtsROUTINE AVERAGE (AVG,X,Y)


REAL AVG,X,Y
AVG = (x+Y\/2
RETURN
END

PROGRAM TEST
REAL X, Y
v - / a

v - ? n

CALL AVERAGE(4,X,Y)
END

Although this kind of problem seems contrived, it and its variations have historically haunted
FORTRAN programmers"Other languagessuch as Pascalcan also be plaguedby such a problem
t661. I

So what's the lessonto be learnedfrom this example?Don't put a literal as


an input parameterif the routine called modifies the variable.Also, don't write
routineswhich modify an input variablethat is not an output variablewhen using
call-by-address.

3.1.1.3 Call-by-Value versus Call-by-Reference In call-by-value,a copy


of the parameteris placed in the activation record (which resideson the run-time
slack maintained by the run-time memory manager), and so indirect mode
instructionscan be used.The chief drawbackof call-by-referenceversuscall-by-
the compiiermay generatedoubleindirectmode
value is that in call-by-reference,
instructionsincepointersto variablesare passedto proceduresand placedon the
run-time stack.In this case,some form of double indirect addressingis needed.
This is more complex than indirect mode sincesuchinstructionsuse other levels
of indirection and henceone more memory access.
It is important to determine the appropriatecalling mechanismfor different
data structures prior to building the application. The relative advantagesand
disadvantagesof call-by-value versus call-by-reference are dependenton many
things, including the programming language used, compiler implementation,
coding style, target hardware, type of application code, and size of parameters
passed.For example,neverusecall-by-valueto passlarge (or evenmodest-sized)
data structures; use call-by-reference instead. Call-by-value will require the
generationof a very large activation record that could overflow the run-time stack.
Before deciding on a set of rules conceming parameterpassingfor optimum
performance, one should construct a set of test cases that exercise different
variations.Becausethesefactors can vary the instruction mix thesetest casesneed
to be rerun every time the compiler, hardware,or application changesin order to
update the rules.
I LanguageFeatures 63

3.1.1.4 Other Calling Methods Two other calling methodologies, call-


by-name and call-by-value-result,were peculiar to ALGOL-60 and AI-GOL-W
respectively.We are not concemedwith the particularsof thesecalling schemes,
but mention them onlv for comnleteness.

NOTE 3.1 There is a humorous,apocryphalstory about Niklaus Wirth,


inventorof Pascal,Modula, and Modula-2, amongother achievements, who was
once askedhow he pronouncedhis name.Wirth is reputedto haveresponded,"If
you call rne by name it's veert, if you call me by value it's worth."

3.1.1.5 Parameter Lists versus Global Variables Global variablesare


available in many languagessuch as C, Pascal, and Ada. In languageslike
FORTRAN they are called COMMON variables,and in BASIC theseare called
COM variables.In any case,global variablesare those within the scopeof all
modules of the software system.This usually means that referencesto these
variables can be made in direct mode, and thus are faster than referencesto
variablespassedvia parameterlists. The decisionto useone methodof parameter
passing or the other represents the tradeoffs between accepted software
engineeringmethodologyand speed.
Using parameterlists is advantageousbecausethe interfacesbetweenthe
modules are clearly defined. Furthermore,in Ada and Modula-2, whether the
parametersare to be input, output, or both is specified.
Unfortunately, parameterlists can get long, and often interrupts are disabled
during parameterpassing (which is in effect a series of LOAD and STORE
instructions).Thus, intemrpt latencymay be increasedin a place where it is least
anticipated and in a way that is hard to spot. Why are interrupts disabled during
parameterpassing?Becauseif they were not, the following scenariocan occur.

I EXAMPLE
3.3
Consider the Pascalfunction with interface containing formal input parameters(called by value) a,
b, c, and d and output parameter(called by reference),o, which dependson the actual values for a,
b. c. and d.

procedure functionl(a,b,c,d : integer, var o : integer);

where the actual parametersr, ), z, and q (which are declared globally) replace formal parameters
a, b, c, d when the procedureis called. The values of x, y, z, and 4 must be pushedonto a stack (using
a series of LOAD and STORE instructions). Supposethat when it is called, procedure function I
pushesx and y onto the stack,but then is intemrpted by a higher-priority processbefore z and 4 can
be pushed onto the stack. The interrupting processmay alter the values of x, y, z, and 4, and then
complete.When function I resumes,the new values of z and q arepushedonto the stack along with
the old value of x and y-a potentially catastrophicsituation if x, y, z. and.q need to be correlated
(time-relative). Thus, to prevent this occurrence, interrupts are , disabled during parameter
passlng I
64 Chap. 3 I LanguageIssues

Global variables,althoughthey introduceno subtletiming problems,can be


dangerousin that accessto suchvariablesmay be madeby unauthorizedmodules,
thus introducing bugs that are devilishly hard to find. For example,in FORTRAN,
mismatched COMMON overlays are notoriously elusive. For these and other
reasons,overuseof global variablesis to be avoided(see[165]).
The choice of parameter-passing techniquesis difficult, but the rule of
thumb is to use parameterlists as long as timing is not affectedunacceptably
(althoughthis is difficult to predict). Global passingshould be used only when
timing warrantsit, and it shouldbe clearly documented.The final systemusually
employs all parameter-passing techniquesin some combination,reflecting the
tradeoff.sbetweengood software engineeringtechniqueand the realities of timing
constralnts.

3.1.2Recursion
Many programminglanguagesprovide a mechanism,calledrecursion,wherebya
procedure can be self-referentiai;that is, it can call itseif. Because of the
Recursion Theorem, all functions on integers can be written as recursive
procedures.The following exampleillustratesa recursiveprocedure.

I EXAMPLE
3.4
This Pascalprocedurecalculatesthe greatestcommondivisor of two positiveintegersusing Euclid's
algorithm.

procedure gcd{x, y : incegrerl; trecursive procedure}

begin
if (Y = O) then {GCD found}
writeln (x)
els e
Scd(y, (x mod y) ) { roe rrrqi \/a ct cn l

end; T

Although recursion is elegant, its adverse impact on real-time perform-


ance cannot be overemphasized. Procedure calls require the allqcation of
storageon one or more stacks for the passing of parametersand for storageof
local variSbles.The execution time needed for the allocation and deallocation.
and for the storageof those parametersand local variables, can be ill-afforded.
In addition, recursion necessitatesthe use of a large number of costly memory
indirect and register indirect instructions. Moreover, the use of recursion often
makes it impossible to determine the size of run-time memory requirements.
Finally, re-entrant code often includes critical regions that must be protegted
by semaphores(see Chapter 11). Thus, iterative techniquessuch as loops must
Sec.3.1 I LanguageFeatures 65

be used in those languagesthat do not support recursion,and when real-time


performanceis crucial.
This is not to suggestthat recursionis a detriment to a language;on the
contrary, it promotes a top-down and structuredstyle. However, in real-time
systemsthis benefit may be offset by the deleteriousimpact on performance.
In retrospect,it would be nice if the compiler would allow the programmer
to write recursiveroutines,so that he or she could take advantageof the more
elegant representation,and then let the translationprocessmap the code into
either recursive or iterative form in order to optimize performance.Some
compilersmay do this, althoughthe author is unawareof any.

3.1.2.1 Re-entrantProcedures Languagesthat allow recursiondo so by


supportingre-entrantprocedures.A re-entrantproc'edLtrecan be usedby several
concurrentlyrunning tasksin a multitaskingsystem.
LanguagessuchasAda, C, Modula-2,and Pascalprovide fbr re-entrantcode
and thus recursion,whereassome older versionsof FORTRAN compilers and
BASIC interpretersdo not.
In the absenceof re-entrancy,awkward schemesare sometimesneededto
allow severalprocessesto sharecode. For example,many older FORTRAN IV
compilers,which did not supportre-entrancy,neededseveralversionsof the same
SUBROUTINE, with differentnames,which could only be calledby one task.For
example, two SUBROUTINES.foT matrix multiplication called MULT1 and
N4ULTZ,identical in all but name, would be neededto allow two different tasks
to perform matrix multiplication.

3.1.3DynamicAllocation
The ability to dynamically allocate memory is important in the construction and
maintenance of stacks needed by the real-time operating system. Although
dynamic allocation is time-consuming,it is necessary.Languagesthat do not
allow dynamic allocation of memory require a stack of fixed size. Although it is
faster to maintain a fixed size stack, flexibility is sacrificed, and the maximum
size of the stack must be known a priori.
Linked lists,trees,heaps,and otherdynamicdatastructuresusedin real-time
applications can benefit from the clarity and economy of memory introduced by
dynamic allocation-at the expenseof speed,of course.
Fbr example,the NEW statementin Pascaland the malloc0 procedurefound
in C are used to dynamically allocate storage.(As a language,C does not really
supportdynamic allocation.)The mallocQ library function call invokesan operating
system call that managesmemory requests.)There are, of course, corresponding
constructs(DISPOSEin Pascal,and free0 in C) to de-allocatestorage.
Finally, Ada and Modula-2 have dynamic allocation facilities, whereas
BASIC and most versions of FORTRAN generally do not.
66 Chap. 3 I LanguageIssues

3.1.4Typing
The notion of typing was introducedby ALGOL-60 and has been implementedin
most modem languages.Typed languagesrequire that each variable and constant
be of a specifictype (e.g.,integer,real, character,etc.) and that it be declaredas
such before use. Strongly typed languagesprohibit the mixing of different types
in operationsand assignments.

3.1.4.1 Advantagesof Strong Typing Stronglytyped languagesforce the


programmerto be preciseabout the way data are to be handled.In addition, strong
typing can prevent unwantedor unnoticed molestationof data through truncation
or rounding.
Ada, Pascal,Modula-2, and C all have somelevel of type checking.While
FORTRAN has the notion of a typedvariable,it is not stronglytyped, which can
leadto problems.To illustratehow implicit variabletyping in FORTRAN canlead
to problems,considerthe following:

I EXAMPLE
3.5
In FOMRAN the following loop construct usesvariable I as a loop index to executethe loop body
five times. The statement "20 CONTINUE" marks the end of the loop body. There is an error,
however, in that there is a period instead of the desired comma between the I and the 5

DO20 I = 1.5

2C CONTL\l'r.itr

Since FORTRAN generally ignores spaces.and undeclaredvariables starting with the letter "D" are
assumedto be REAL, the replacementof "," by "." causesthis statementto be interpretedas

DO20r=1.5

where DO20I is a REAL variable. The problem is further compounded in that the matching
statement

2O CONTINUE

is not seen to be extraneous,h situation that could not happen in C or Pascal. t

This scenariocausedthe loss of a U.S. spacesatellitein the 1970s.

3.1.4.2 Disadvantages of Weak Typing Languagessuch as C which are


typed, but do not prohibit mixing of-types in operations,can causerounding and
truncation problems.In addition, C-fenerally performs calculation at the type that
has the highest storagecomplexity. That is, it "promotes" variables to the highest
Sec. I LanguageFeatures 67

This can generate"unseen"and time-consuming


type necessary. instructionsto
performthe promotion.

I EXAMPLE
3.6
The fbllotvingC-codefragnrentillustratesautomaticpromotionand dernotionof variabletypes.
VariableI is pronrotedto type"tloat" andthe multiplicationis pertbrrredThe resultis theltdemoted
to type "int" bc'fbreassignlnentto variable7

flr-:r L- I n

,l = i=*ft-1p; T

Here the variable i will be promoted to a float r\ pe (real ). and then the
m u l t i p l i c a t i o na n d a d d i t i o n w i l l t a k e p l a c e .A f t e r r v a r d .t h e r e s u l t * i l l b e r r u n c a t e d
and stored in i.
E x p l i c i t t y p e c o n v e r s i o nu s i n g c a s t i n s s h o u l d a l \ \ ' a \s b e u s e d i n C .

I EXAMPLE
3.7
In Example3 6, the line
j=i*k+rrt
shouldbe replacedwith
j = ( i n r ) ( ( f l o a *r k) i+ m )

This explicitlyillustrateswhal was happeningsurreptiliously


befbre t

In addition,if constants
andvariatrles
arenot properlydeclared,unnecessary
hidden promotion instructionswill be generated.For example,considerthe
follovrine:

I EXAMPLE
3.8
This Pascalprogramfragmenthas two real variablesbut a constantof type integer.Somecompilers
r'.rll not convertthe constantto real at compile-time.creatingthe needfor conversionfrom integer
lo real at run-time.

-/ar
x,y: ReaL;

;a ;= y+60;

lle line x := y + 60; should be replacedwith

x.=y+60.0

;--,prerent an unwantedrun-time promotion of the constant I


Chap.3 I LangudgeIssues
68

The same can haPPenfor variables:

3.9
T EXAMPLE
Consider the C-code fragment.

float x,Y;
int z;

x = y+z;
instructions generatedby the
Variable z is promoted to type float. The LOAD and "convert-to-float"
FLOAD (floating variable LOAD)' This kind of waste is
compiler probably take longer than the
,yi**r. If z cannot be of type float' it should be explicitly cast: that is'
discouragedin real-time
use
x-Y+(float)z I

c, both
whereas Pascaldiscouragesmixed-type usagemore vigorously than
Ada and Modula-2 completely plohibit mixed-type calculatioris.

3.1.5ExcePtionHandling
or other anomaly
certain languagesprovide facilities for dealing with errors
program execution. Such situations are called
conditions thai arise during
exception occurs, a certain code is
excepti'ons[79].During run-time, when an
invoked to handle it. such code is called an exception handler.
in certain
conditions such as divide-by-zeroelrors, floating point operations
but are handled in
cPUs, and the like, are normally considered exceptions
exceptional conditions at the high-
microcode. The ability to define and handle
orderlanguageleveldistinguishestrueexceptionhandling.
explicit
of all the languagesdiscussedin this chapter, Ada has the most
capability
exception-handlingiaciiity. ANSI-C provides someexception-handling
through the use of signals.
such as
Finally, exception handling can often be implementedin languages
permitted by the
C, pascal, and Modula-2 as a user-definable library when
comPiler.

3.1.6AbstractDataTYPing
to compute
The ability to represent abstract ideas succinctly is as important
provide facilities for the
Ianguagesas it is to human ones. certain languages
simple numbers
abstract representationof entities that cannot be handled by
capability tend to make program design easier and cleare
Languageswith such a
to an outside observer.
datt
Abstract data typing includes the ability to represent and manipulate
typesthatarenotasnnaarotypesupportedbythelanguage-forexample,tht
type describedlate
complex datatype defined in Example 3.13 and tlie stackdata
I Language Features 69

To a lesserextent, enumeratedtypes andtype definitian provide methodsfor


implementing data abstracrion.Enumeratedtypes are illustratid in Example 3.10,
while type definitionis illustratedin Example3.11.LanguagessuchasAda,pascal,
ANSI-C, and Modula-2 provide enumerateddata types to handle suchentities.

I EXAMPLE
3.10
Use of enumerationtypes in Ada:

Iype DAY is (MoN, TUE, WED, THU, FRT, SAT, SUN);


t y p e V O L T A G Bi s
defta 0.01 range 0..0 . . 5.0;
T y p e C O L O Ri s ( R E D . G R E E N , B L U E ) ;

The specification of enumerateddata types is similar in Pascal and Modula-2. In ANSI-a there
is
no equivalent for the VOLTAGE type, but the others would be

ENum DAY {MON, TUE, WED, THU, FR], SAT. SUN};


enum COLOR{RED, GREEN, BLUE}; I
I EXAMPLE 3.11
Useof typedefinitionin C:

/* defines a data type ,,string',, as 16 */


characters
typedef char strinStl6l ;

The specification of type definition is similar in pascal, Ada, and iuloaU._2.


I

one drawback of these enumerateddata types is that they only permit the
grouping of similar kinds of data. Ada, c, pascal, and Modula-2, however. all

T EXAMPLE
3.12
In Modula-2 a record type for a personnel record could be

Employee = RECORD
firstName : Array 10. .231 of CHAR;
]astName : Array t0 . .23I of CIIAR;
badgeno : CARDINAL;
ChaP 3 I LanguageIssues
70

Pascal.In c it would look like


The specrficati6nof sucha recordis quite similar in Ada and

stmct EmpLoyee {
char firstname [ 23] ;
char iastname [23] ;
unsignec inc badqeno;
I
]

performanceof
The use of an abstractdatatype doesnot improve real-time
thesystem.Infact,itmaydegradeperformancedependingontheinten
representationformat of the data type involved'

3.l.6.lobject.orientedProgrammingThoselanguagesthatprovide
data abstraction
constructsencouraginga high degreeof informationhiding and
include c++, the interpreted
I
I
are called object-oriented. These languages
and the real-time
l Smalltalk, an object-orientedversion of Ada, Ada++ [46],
l languageDRAGOON [37].
necessary to
1l Object-orientedlanguagesprovide many of the features
encouragegood softwareengineeringtechnique' Formally, object-orientedPro-
gramming languagessuPpoll

r Abstractiondata types
r Inheritance
r PolYmorPhism.
allows the
we have already discussedabstractdata types. object inheritance
terms of other objects so that the new objects
programmerto dlfine new objectsin
For example, an object of type "dog" would
canl*rerit the others'characteristics.
"animals'" Finally,
have at least the same characteristicsas an object of type
function that
function polymorphism allows the programmer to create a single
operatestn different objects depending on the type of object involved.
objectsareaneffectivewaytomanagesystemcomplexity,astheyprov
hiding' In
a natural environmentfor encapsulation,which is similar to information
performed on them
encapsulation,a classof objects and the operationsthat can be
(called methods) are enclosed or encapsulated into packages called c/css
data only by
definitions. An object can utilize another object's encapsulated
of the method to apply.
sending a messageto that object with the name
have a
For example, consider the problem of sorting objects. We might
For a class of
method for sorting an object class of integers in ascendingorder.
For a class of objects that have an attribute
people, we might sort them by height.
to the rainbow. Because these
tf *lor, we might sort them by color according
if another
objects have similarly named methodswith different implementations,
must resolve
oui".t scndsa messageto sort one of theseobjects,the run-time code
penalty'
*ti"tr method to apply dynamically-with sigriificant execution time
I Language Features 71

For example,in onestudy,codewrittenin objective-c,anotherobject-oriented


variantof C, was43Voslowerthancodewritten in conventionalC [26]. In addition,
programs written in the (interpreted)language Smalltalk, are known to be
approximately5 to 10 times siowerthanthosewritten in conventionalC [73].
The executiontime penaltyin object-orientedlanguagesmay be due,in part,
to their relative immaturity.But in compiled object-orientedlanguages,it seems
clear that the requirementsfor late binding (run-time as opposedto link-time)
necessitatedby function polymorphism and inheritanceare considerabledelay
factors.
In both interpreted and compiled object-orientedlanguages,additional
delays result from automatic storagemanagement(including garbagecollec-
tion-see Chapter 8) needed by objects over their lifetime. For example,
Ingalls[73] mentionsthat for programswritten in Smalltalk,I}Vo of theexecution
time is spentin automaticstoragemanagement.
Nevertheless,the promise of object-orientedprogramming languagesin
real-time applications lies in clearer design and better maintainability. The
shortcomingsof object-orientedlanguagesin real-time will be overcome.For
example, hybrid languagesthat reduce the amount of late binding required are
alreadybeing used[27], andbettermethodsfor automaticstoragemanagement(as
well as faster computers) will make the use of even interpreted object-oriented
languageslike Smalltalkviable for usein real-time.One thing is certain-we can
look forwaid to the increaseduse of object-orientedlanguagesin real-time.

3"1.7Modularity
Pamas[125] presentsa set of criteria that can be used in partitioning software
systemsinto modules in a way that both clearly defines intermodule communica-
tion and preventsunwanted intermodule interference.From a software engineer-
m_sperspective,modular software is highly desirable.But there is a price to pay
rn the resultant overheadassociatedwith procedure calls. This affects real-time
performanceadverselyand should be consideredin the system design.
The most important conceptin defining modularity is the ability to perform
information hiding. We will discussthis concept further in Chapter 4. However,
note that it is of the utmost importance that code modules be treated as "black
t'o.xes,"with the inner workings of the module invisible to the user, but with the
rnterface to the module clearly defined. Certain languages have constructs
designed to promote such techniques, while others do not. For example, the
conc€pt of the MODULE is implicit in the langupge Modula-2. A MODULE
rorrsistsof a set of clearly defined input and output parameters,local, invisible
r-ariables,and a seriesof procedures.
In Ada the notion of a package exquisitely esrbodiesthe conceptof Pamas
intomration hiding. The package consists of a package specification and
dEclaradons,whichincludeitspublic orvisibleinterface,anditsprivateorinvisible
mts. ln addition the package body, which has additional extemally invisible
72 Issues
Chap.3 I Language

components,contains the working code of the package.Packagesare separately


compilable entities, which further enhancestheir application asblack boxes.

3.13
T EXAMPLE
This Ada packagedefines a data type called "complex" and a set of operations to be performed on
it. Notice that a complete set of binary, unary, and relational operations must be defined.

package COMPLEX-NUMBERS rs

-- define complex data tYPe

type COMPLEXrs
record'
REAL-PART : F L O A T : = 0 . 0 ;
IMAG PART : F L O A T : = 0 . 0 ;
end record;

function E Q U A L ( X , Y : C O M P L E X ) return BOOLEAN;


function "+" ( X , Y : C O M P L E X ) return CoMPLEX;
function '-" ( X , Y : C O M P L E X ) return COMPLEX;
function "*' ( X , Y : C O M P L E X ) return COMPLEX;
function "/" ( x , Y : C O M P L E X ) return COMPLEX;
end;

-- define operations on data tYPe

package body COMPLEX-NUIIBERS rs


function EQUAL(X,Y : COMPLEX) return BOOLEANis
begin
if (X.REAL-PART = Y.REAL-PART) and (X.IMAG-PART
Y.IMAG-PARI) then
return TRUE;
else
return-FALSE;
end if;
CNd EQUAL;

function "+" (X,Y : COMPLEX) return COMPLEXiE


begin
retuTN (REAL-PART => X.REAL PART+Y.REAL-PAR.T,
IMAG-PART => X. IMAG-:PART+Y. IMAG'PART') ;
€Dd "+t; :
Sec. 3.2 I Survey of Commonly Used programming Languages
73

function "-,' (X,y : C O M P L E X )r e t u r n C O M P L E Xi s


begin
TELUTN (REAL_PART => X.REAL PART _ Y.REAL-PART,
r M A G _ P A R T= > X . I M A G _ P A R T - y . I M A G _ p A R T ) ;
en.1 ,t _,' .

function "*" (X,y : COMPLEX) return COMpLEX is


begin
return (REAL_PART => (Z.REAL_PART * y.REAL_PART)
_ (X.IMAG_PART * Y.IMAG-PART),
IMAG-PART => (x.IMAG_PART * y.REAL_PART)
+ (X.REAL_PART * Y.IMAG-PART));
^ r A u * n .

function t/" ( X , . y : C O M P L E X )r e t u r n C O M p L E Xi s
begin
return (REAL_PART => ( (x.REAL_PART * y.REAL_PART)
+ (X. IMAG_PART * y. IMAG_PART)) / ( (y. REAL_PART *
Y . R E A L _ P A R T ) + ( Y . I M A G - P A R T * Y . I M A G - P A R T )) ,
IMAG_PART => ((X.IMAG_PART * y.REAL_PART)
_ (X.REAL-PART * Y. IMAG_PART) ( (Y.REAL_PART *
)/
Y.REAL_PART) + (y.IMAG_PART * y.IMAG_PART) ) ;
erld ', /', ; I

SURVEYOF COMMONLY
USEDPROGRAMMING
I-ANGUAGES

This section suflrmarizesthe key features of programming languagesthat have


been widely used in the development of real-time software. In particular, it
focuses on those language features just discussed. The highlights of this
discussionare summarizedin Table 3.1.
Chap. 3 I LanguageIssues
74

of VariousLanguages
TABLE 3.1 FeatureComparison

Call-by- Call-bY- Dynamic Strong TYPe ExcePtionEnumerated Re-entrant


Typing Intemrpt Handling Type Modularity Code
Language Value ReferenceAllocation

Ada v v v v v v v v
nla nla n n n n n n n
BASIC
C y y * y n n v v v v
n y n n n n n
FORTRAN
Modula-2 v y y v v n v v v
Pascal v v v v n ll
v v v
* Simulated.

3.2.1BASIC
The BASIC programminglanguagewas introducedat DartmouthCollege in the
mid-1960s to introduce studentsto computersvia an easy-to-leam,interactive
language. BASIC was originally designed as an interpreted language' ln
interpretedlanguages,the source code is not compiled; rather, it is a set of
directives to another program, the interpreter, which is constantly running.
Interpretedlanguagescan pelforrn syntax checking as the program is typed in, and
thus they tend to help the programmer avoid syntactical errors. Interpreted
languagesare slow, however-often a thousandtirnes (or more) slower than an
equi,valentcompiled language'
Thus,in its interpretedform, BASIC is wholly unsuitedto real-timesystems
And althoughthereare compiledversionsof BASIC which are much faster,these
are also undesirable.BASIC is a weakly typed language,with little or no
provisions for modular design,exceptionhandling, or abstractdata typing' All
variablesare global in natureand thereis no mechanismfor passingparameters
(which is
ln fact, the language encouragesthe use of the GOTO statement
consideredharmful U65]), and thereis no supportfor re-entrantcodeor construct
suitable for building intemrpt handlers.Finally, it is unstandatdized.

3.2.2 FORTRAN
The FOMRAN language is the oldest high-order language extant (developed
circa 1957). Because in its earlier versions it lacked recursion and dynamic
allocationfacilities,real-timesystemswritten in this languagetypically included
a large portion of assemblylanguage code to handle interrupts, scheduling, and
low-level I/O (communication with extemal devicesthrough the use of memory-
mappedI/O, DMA, and I/O instructions). Later versionsof the languageincluded
such features as re-entrant code, but even today, a FORTRAN solution requires
some percentageof assemblylanguagecode to accompanyit'
Sec. 3.2 I Sunev of Commonly Used programmingLanguages /5

NOTE 3.2 FORTRAN was developedin an era when compilers were


suspect,and efficient code was essentialto wringing performanceout of small,
slow machines.As a result,the languageconsrructswere selectedfor efficiencv.
and early FORTRAN code generarorswere unusuallyso.
To its detriment, FoRTRAN is weakly typed, but because of the
SUBROUTINE constructand the IF-THEN-ELSE constructintroducedin later
versions,it can be usedto designhighly structuredcode.FORTRAN hasno built-
in exceptionhandlingor abstractdatatypes.FORTRAN is still usedto write real.
time systems in scientific, avionics, and process-controlapplications.Many
versions of the FORTRAN language are available, including FORTRAN IV
FORTRAN 77, and rhe laresrISO standardFORTRAN 90.

3 .2 .3C
The c programming language,invented around 1971, is a good languagefor
"low-level" programming.That is, machine-related objectslike characters,bytes,
bits, and addressescan be handleddirectly through the language.Theseentities
must be manipulatedto control intemrpt controllers,CpU registers,and other
hardwareneededby a real-time system.
until recently the languagewas not standardized,and the text written by
Kernighan and Ritchie [80]-the inventors of the language-was the de
facto
standard.ANSI-C has since been defined,however,with resultantbenefits.
c providesfor global variablesand call-by-value.call-by-referencecan be
simulatedthrough the use of pointer types.The languageis inherentlymodular,
and recursive, and provides for dynamic memory allocation through library
routinesand pointertypes.

3.2.3.7 special, variable Types c also provides special variable types


such as register,volatile, static, and constant,which allow for control of code
generationat the high-orderlanguagelevel. For example,declaringa variableas
a register type indicates that it will be used frequently. This encouragesthe
compiler to place such a declaredvariable in a register,which often results in
smaller and faster programs.
variables declaredas type volatile are not optimized by the compiler.This
is useful in handling memory-mappedI/o and other instanceswhere the code
should not be optimized.

I EXAMPI-E
3.14
In the following C-code fragment, the low-order bit of memory-mapped I/O location ourport is
strobed.

- n ,
_ 1 .
Chap. 3 I Language Issues
76

you can prevent the compiler from optimizing this ostensibly redundant code by declaring outport
I
as type uotatlte. .-

Type staticvariablescan be usedto provide'privatecommunicationbetween


modules.The following exampledemonstrates the use of staticvariablesas well
as the construction of an abstractdata type in C.

3.15
I EXAMPLE
The following set of modules, stored in the same source file, can be used to implement the abstract
of,
notion of a Stack.The use of the static data type limits accessto, and hides the implementation
within this set of modules. Furthermore, their value upon exiting
the stack top and the stack itself
is only
is preservedupon exiting any one ofthese routines. Interface to the stack from other routines
throueh the PUSH, POP,and init routines.

maximum stack stze */


#deflne MAXSIZE1000 /* arbitrarY
ll,
I

llllr int toP;


static
I char stackIMAXSrzEl ; /* Lhe stack itself
static
li

void init ()
{
top-0; /* reset to bottom of stack

int pop(void)
{
int temp;
temp=stackItoP]; /* remove data from stack
t ^ n - - .
uvv /* decrement toP Pornter

return(temp);
]

void push(int data)


t
top++; /* increment top Pornter

stack Itop] =data; /* push data onto stack


I

Note that stack underflow and ovelflow are not treated; they are left as an
exercise.
Finally, variables declaredas type constantcan be forced into the ROM area
of memory at link time. This is particularly useful in lining up the logical memory
map with the physical hardware memory map'
Sec. 3.2 I Survey of Commonly LlsedProgrammingLanguages 77

3.2.3.2 Exception Handling The C language provides for exception


handlingthroughthe use of signalswhich are discussedin Chapter7. In addition,
two other mechanisms,setjmp and longimp, are providedto allow a procedureto
return quickly from a deep level of nesting, a useful feature in procedures
requiring an abort.The setjmpproceclurecall, which is really a macro (but often
implementedas a function), savesenvironmentinformationthat can be usedby a
subsequentlongjmp library function call. The longjmp call restoresthe program
to the state at the time of the last setjmp call. Procedureprocessis called to
perform someprocessingand error checking.If an error is detected,a longlmp is
performedwhich changesthe flow of executiondirectly to the first statementafter

T EXAMPLE
3.16
Considerthe following C program which performs a genericprocess

<signal.h> /* contains setjrnp and longtjmp proLotypes */


#include

longt jmp/buf l16l /* define environment type */


typedef
jmp-buf env; /* holds environment */

hain o
I

, /* d o s o m e p r o c e s s i n o */

if (set.jmp (env) == 0 ) /- reLurn trom longjmp or ttornaf return?


process ( I ; ,. per form normaf processing */

e 1s e
/* */
^ L ^ - F - - - ^ ^ ^ - d / \ .
a u v r u J ! v u e D - \ r , / !TEaLr ul lrt rhr as de rvr ri u
: rl n
v rn laYi Jmr n( ! P urifh orror

process ( )

,/* return value to setjmp */


int value;

/* do some processjng*

(no error) / * error occurred? *


if

/* n^ 6rr\r -- nnrm>l h
p rr ^ ^v ^u -c -Di - f rLv - /

^ t ^ ^

iongjmp(env,value) /; /* error, abort

I
Issue
Chap.3 I Language

the last setjmp-the abort process procedure in main. The processing done in
procedure process prior to the abort is lost (unless global variables were
changed).

3.2.3.3 Disadvantages of C To its detriment, C is weakly typed, although


the ANSI-C version has somewhatstrongertyping. ANSI-C has addedthe concept
of enumerationtypes, but abstractdata types are bettel handled by c++.
overall, however, the c language is good for real-time programming
because it provides for structure and flexibility without complex Ianguage
restrictions.

3.2.4C++
C++ is an object-orientedprogramminglanguagethat was originally implemented
as a macro-extensionof C. Today, C++ standsby itself as a separatelycompiled
language,althoughstrictly speaking,C++ compilers shouldacceptstraightC code
C++ exhibits all three characteristics of an object-oriented language. It
promotes better software engineering practice through encapsulationand bette
abstractionmechanismsthan C. Significantly' more real-time systemsare being
constructedin C++, and many practitioners are asking, "Should I implement the
systemin C or C++?" My answerto themis always"it depends."ChoosingC in lieu
of C++ in real-time embeddedapplicationsis, roughly speaking,a tradeoff betwee
a,,lean and mean" C program that will be faster and easierto predict but harder tc
maintain and a C++ piogtu. that will be slower and unpredictablebut potential\
easierto maintain.I say"potentially" becauseit remainsunprovenwhethermany ol
the advantagesof C++ (namely,easiermaintainability) are really there'

3.2.5Pascal
pascal was designed in 1968 by Niklaus Wirth as a teaching tool-he neve
intended to implement it as a language for professional or production use. Thr
first functionaf compiler was introduced around 1971. ?ascal is elegant in it
simplicity, and there exists a widely accepted (but often violated) ANSIAEEI
standard. pascal includes such features as strong typing (although not stron
enough), recursion, dynamic data structures through pointer types, enumerate
types for data abstraction,and an enforced high degree of modularity'
Nevertheless,Kemighan [79] has developed strong argumentsagainst th
w
use of pascal for writing "real" programs. Since his points :ue so compelling,
shall quote them directlY'

1. Since the size of an array is part of its type, it is not possible to writ
general-purposeroutines-that is, to deal with arrays of different size
In particular, string handling is very difficult'
I Survey of Commonly Used ProgrammingLanguages

2. The lack of static variables,initialization, and a way to communicate


nonhierarchicallycombine to destroy the "locality" of a program-
variablesrequire muc*t more scopethan they ought to.
3. The one-passnatureof the languageforces proceduresand functions to
be presentedin an unnaturalorder: the enforcedseparationof various
declarations scatters program components that logically belong
together.
4. The lack of separatecompilation impedes the developmentof large
programsand makes the use of libranes impossible.
5. The order of logical expressionevaluationcannotbe controlled,which
leadsto convolutedcode and extraneousvariables.
6. The casestatementis emasculatedbecausethere is no default clause.
7. The standardI/O is defective.There is no sensibleprovision for dealing
with files or program argumentsas part of the standardlanguage,and no
extensionmechanism.
8. The language lacks most of the tools needed for assembling large
programs, most notably file inclusion.
9. There is no escape. The language is inadequate but circumscribed,
becausethere is no way to escapeits limitations. There are no casts to
disable type-checking when necessary.There is no way to replace the
defective run-time environment with a sensibleone, unless one controls
the compiler that defines the "standardprocedures."The,languageis
closed.

The author tends to agree"with this assessmentand would add that Pascal
generallydoesnot provide intemrpt function types,which complicatesthe writing
of intemrpt handling routines. The use of the semicolon as a statementseparator
rather than a statementterminator leads to confusion and prolongs the coding
process.Although various implementationsof the languagebypasssome of these
problems,this is not true for all. In general,Pascalis not recommendedas a real-
time language.

Modula-2

In 1975 Niklaus Wirth developed a languagespecifically for multiprogramming


systeins-Modula. In 1977 as part of a researchproject to develop computer
hardwareand software specificationssimultaneously,Wirth developedModula-2,
a languagewith features similar to both Pascal and Modula'
Modula:2 includes all aspectsof Pascaland extendsthe languagevi,ittrthe
concept of a module or program package.A module is divided into a definition
part and an implementation part, and is crucial to a multitasking system. In
addition, Modula-2 has the following languagefeatures:
80 Issues
ChaP.3 I Language

1. The concept of a procesJ or thread-of-execution as the key to


multitasking facilities.
2. Low-level facilities such as an intemrpt proceduretype, which makes it
possible to interact directly with the underlying hardware.
3. A procedure type that makes it possible to assign variables
dynamicallY.
4. Clearly defined interfaces between modules in terms of the modules'
import lists.

In addition, many of the Pascalfeatureslisted as detrimental in the previous


section have been eliminated.
Because of its rnultitasking orientation, Modula-2 lends itself well to
implementation in real-time systems.

3.2.7 Ada
In the late 1970s,Department of Defensel analystsbecameconcemedthat large
quantitibs of expensive software were being produced in several different
languages,often for the samepurpose.In order to reducecostsand to standardize
the languagein which software was developed,a bidding processwas createdto
select the appropriatelanguagefor the 1980s and beyond.
After a rigorous .and competitive selection process,the Ada languagewas
bom. Designed specifically for real-time embedded applications, it is truly a
language of consensus.This language has been mandated as the language of
choice for all DoD software"But becauseof the early lack of good compilers, too
few Ada programmers,difficulty of program construction,and the inefficiency of
the language,less software has been written in Ada than had been hoped.
The statedfoci of the Ada languagewere [7]

1. Program reliability and maintenance.


2. Programming as a human activity.
3. ProgramefficiencY.

The first of these considerationsis addressedthrough the use of extensive


compile-time type checking. This minimizes run-time errors and error checking,
which take time (although Ada does include provisions for run-time elror
checking through, for example, range checks). In addition, the concept of
separatelycompilable modules, packages,or units provides for easy program
development and maintenanceby large teams of programmers,and an explicit
exception handling capability provides for robust elror recovery. Finally, strict
type checking and enforcementprevents unwmted or undesirabletype conver-
sions from occurring.

I DoD is the largest single purchaserof software,in the world.


Sec. 3.2 I Survey of Commonly Used ProgrammingLanguages 81

The human aspectof programmingis treatedin the form of abstractdata


typesas well as the programmingstyle enforcedby the language.This notion led
to the decision that program readability would be emphasizedover ease of
program construction.Although the languagewas meant to be compact in its
syntax,the designershave arguablyfailed in this intent.
Program efficiency has been one of the most debatedaspectsof the Ada
language.Early compilersfor the languagewere difficult to write and generated
poor code (in termsof executiontime). Newer compilershave beenmore readily
produced but have also been criticized for their real-time performance. One
feature of the Ada language that does portend efficient operation is the Ada
multitasking/multiprocessingmodel which allows modules to be written directly
for independenttasks/processors. This greatly reducesdevelopmenteffort and
increasesefficiencyin multiprocessingsystems.Of the otherlanguagesdiscussed,
only Modula-2 has a similar facility.
As mentioned,Ada is a strongly typed language,orovides for dynamic
allocationand recursion,has an explicit exceptionhandling capability,abstract
data types,low-level programmingfeatures,and separatecompilationfacilities.
In addition, it has an explicit intem.rpttype used in the construction of intemrpt
handlers. These features seem to make Ada an exceptional choice for a real-
time language, which it was intended to be. However, the sheer bulk of the
languagehas renderedit less efficient than it would have to be for use in some
applications.

Ada 95

.\lthough the original Ada language(now casuallyreferredto as Ada 83) was


rnrendedspecifically for embeddedreal-time systems,as noted it has experienced
significant problems. Systemsbuilders have typically found the language to be
roo bulky and inefficient. Moreover, significant problems were found when trying
ro implement multitasking using the limited tools supplied by the language,such
ru the roundly criticized rendezvous mechanism. This construct, intended to
o'anagreementto meet with a friend
provide synchronization,has been likened to
but not when nor where."Limited control of prioritiesleadsto priority inversions
rdiscussedlater). The uncertainty of these and other mechanismshas made the
languagenot just "slow" but,.more importantly, unpredictable.
The programming language community has long been aware of the
problems with Ada, and practically since the first delivery of an Ada 83
s-onipiler,has been rneeting regularly to discuss a new version of the language"
R.etened to as Ada 9X during its development, the new version has frozen
Ianguage changes. The. new language, now called Ada 95, is the first
lmemationally standardizedobject-oriented programming language. It revises
md supersedesthe 1983 standard.
Some of the new tasking featuresof the languageare
[ssues
ChaP'3 I Language
82

that controls how tasks are


r A pragmo rask-Di-spatchins-Policv
disPatched'
rApragmsLcckingi-Policythatcontrolstheinteractionbetweentas
scheduling'
r A p r a g m a Q u e u i n g - P o i i c y t h a t c o n t r o l s t h e q u e u i n g ppolicies
o l i c y . oare
ftas
,"rour;. queues.First-In-First-outandpriority queuing
"rrtiy
available'

Thesethreepragnraswereclearlydesignedtoresolvesomeoftheuncerta
synchronization-'
scheduling,resourcecontention'and
ott,","^punsionsofthelanguagewereintendedtomakeAda95anobje
orientedlanguage'Theseinclude:

r TaggedtYPes
r Packages
i
rll r Protectedunits'

Properuseoftheseconstructspermitstheconstructionofobjectsthat,exhibi
languages'Discussionof this aspectof Ada
three characteristicsof object-oriented
the iext. For more information,see[116]'
95, however,is beyond the Scopeof For additional
w".r.ing of Ada 95 ur" becoming widely available'
""#on,
informationontheuseofAdag5inreal-timesystems,see[15].Forup-to
minuteinformationandadditionaldetailsonotherfeaturesofAda95,chec
I many free tutorials'
Intemet Ada user groups for one of the
l
I
I
3.2.9AssemblYLanguages
In ChaPter2 we discussedthe vari'
y'
underlying computer architecture'
features discussedfor the high-levr
that it Provides more direct contr
becauseof its unstructurednature
to leam, tedious, and
machine, .;;; ill assemblylanguageis usually difficult
elror prone''The resulting code is
Until recently' most assembl
that was more efficient than th
improvements in optimizing comptlers'
languageprogrammerscan generatecode
assemblycode exists only in caseswher
best compiler"r.Thur, the need to write
thecompilerdoesnolsupportcertainmacroinstructions,orwhenthet
constraintsaresotightthathand-tuningisneededto.produceoptimal.code o
t a"systemwill likely Jmploy a 90/10 solution-thatis,909o
";r*; language,while the rest is written i
the coclewill be written in the high-ordei
assemblYlanguage'
Sec. 3.3 I Code Generation

NOTE 3.3 The 90/10 solution theme,which is also known as the Pareto
Principle, has many variations.One statesthat 90Voof a softwareproject takes
5O7oof thetime, whereasthe other lOVoalsotakes507oof the time' Another states
that l\Vo of the code executes907oof the time'

provide a pragma pseudo-opwhich allows for assemblycode to be placedin-line


with the high-orderlanguagecode.
In summary,assemblylanguageprogrammingshoulcibe limited to use in
situations or in controlling hardware features that are not
iming situati
volry tlrght timing
supportedby the compiler' In general,it shouldbe discouraged'

3.3 CODEGENERATION
The way in which the compiler will map your code into machinelanguageis as
important as the code you write yourself. The output of the compiler can be
jumps, and so on,
affectedby optimizationfor speed,memory and registerusage,
which can lead to inefficientcode,timing problems,or critical regions.Thus real-
you
tlme programmersmust be mastersof their compilers.That is, at all times
must know what assemblylanguagecode will be output for a given high-order
languagestatement'

KnowYourComPiler
Understanding the mapping between high-order language input and assembly
languageoutput for your compiler is essentialin generatingcode that is optimal
in eittrer execution time or memory requirements.The easiestand most reliable
$.ay to leam about your compiler is to run a seriesof tests on specific language
constructs.
For example,in many C and Pascalcompilersthe casestatementis efficient
onl1,if more than three casesare to be compared-otherwise nestedif statements
quite
shouldbe used.Sometimesthe code generatedfor a casestatementcan be
;onvoluted-for example, a jump table with an offset table. The code then
pertormsan indirect jump through a register,offset by the table value' This can
t'e time-consuming.
We have alreadymentionedthat procedurecalls cost time; that is, overhead
r,nvolvedin the passlngof parametersv^iathe stack.You should determinewhether
byte rrr by word'
-1'ourcompiler passesthe parametersby 'the
Goo-d compilers in any language should provide optimization of
in
i-rrembly language code output. Some of these techniques are discussed
Chapter9.
E4 Chap. 3 I LanguageIssues

f EXAMPLE
3.17
Consider the following tu,o mixed listings consisting of a C-code fragment and the compiler
output:

int i = 4;
l-uAU K.l-,4 toao regrster l w1tn 4
S T O R ER 1 , i . s t o r e r e g i s t e r 1 inlo symbofic focalion i

i - f i - A .

S T O R E4 , 1 store 4 into symbolic location i

The first listing illustrates a compiler that registerizesthe variable for potential reuse.While
this method initially generatestwo instructions,in the long run it may be more effective. If, however,
the instruction occurs inside a tight loop or during a critical time period, the second method
illustrated may be favorable. I

Analysis
3.4 Schedualability

This chapter focused on those language features that minimize the final code
execution tirne that lend themselvesto performanceprediction. The compile-time
prediction of executiontime performanceis known as schedualabilityanalysis.In
the design of modern real-tirne languages,the emphasisis on eliminating those
i constructsthat render the language nonanalyzable.For example, the following
I
I common laneuageconstructsare taboO:
i
I
I
i,.l
T Unboundedrecursion
;l I While loops
T Intemrpts

Most so-called real-time languagesmust eliminate all of these constructs.

3.5 EXERCISES
1. Why is BASIC a bad language for real-time design?
2. Why is Modula-2 a good language for real-time design?
3. Ada is designed for embedded hard real-time applications and is intended to suppolt
static priority schedulingof tasks.The definition of Ada tasking, however, allows a high-
priority task to wait for a low-priority task for an unpredict4ble duration. Discuss
potential problems with this scenario.
4. Rewritg Euclid's algbrithm shown in Example 3.4 in
(a) Ada using recursion..
(b) Modula-2 using recursion.
(c) C using recursion.
(d) FORTRAN.
Exercises 85

(e) BASIC.
(f) Assembly languagefor a 2-addressrnachinewithout recursion.
(g) C++.
5. In one of the languagesmentionedin this chapter(exceptBASIC), write a shortprogram
that acceptsan integer 5 > -r ) I and prints out the English word for that number (e.g.,
"one"). Is it better to use nestedif-then statementsor a casestatement?To answerthis
question,you must examinethe assemblyoutput from the compiler.
6. Do the sameas abovebut accepta number-r € l0 ,1I ,101,100,1l . Is it betterto usenested
if-then statementsor a casestatemen!here?Explain what is happeningin the assembly
languagecode that is generated.
7, Rewrite the enumeratedtype in Example 3.10 in
(a) Pascal
(b) Modula-2
(c) C++
8. Rewrite the complex arithmeticpdckagedescribedin Example 3'13 as
(a) A Modula-2 module.
(b) As a seriesof C procedures.
(c) As a PascalUNIT.
(d) As a set of GOSUB commandsin BASIC.
(e) C++.
9. Examine the assemblylanguagecode generatedby eachof the programsin the previous
problem. Which seems to generate the least number of assembly language
instructions?
10. Rewrite the stack abstractdata type in Example 3.15 to handle stack underflow and
overflow.
11. Which of the languages.discussedin this chapter provide for some sort of GOTO
statement?Does the GOTO statementaffect real-time performance?If so, how?
12. Some software engineers(including the author) believe there is an apparenfconflict
between good software engineering techniquesand real-time performance. Consider the
relative merits of recursiveplogram design versusiterative techniques'and the use of
global variables versus parameter lists. Using these topics and an appropriate
programminglanguagefor examples,compareand contrastreal-timeperformanceversus
good software engineering practices as you understandthem.
The Software
LifeCycle

KEY POINTSOF THE CHAPTER

1
A proper software engineeringframework is essentialfor developing
reliability, maintainability,and cost-effectivereal-timesoftware.
2 . Inherenttradeoffsexist betweengood softwareengineeringpracticeand
real-time performance.
J. Information hiding should be used in the design of reliable, under-
standable,and maintainablereal-time systems.
A
+ . IEEE Std 830 provides a reasonable methodology for software
specification.
5 . DOD-STD-2167A provides a rigorous (if not strict) framework for the
developmentof software.
6. There are numerous other useful standardsfor conduct durine the
softwarelife cycle.

An engineeringapproachto the specification,design,construction,testing,and


maintenance of software is essential for maximizing the reliability and
maintainabilityof the systemas well as for reducinglife-cycle costs.This chapter
looks at one formal model for the softwarelife cycle and discUsses some of the
activitiesthat occur within it.
Although we discussseveraldocumentsthat must be preparedduring the
softwarelife cycle, detailed discussionis prohibited in the interestsof brevity.
The standard set of guidelines for the development of defense-relatedsoftware
and documentation in a strictly controlled environment is DOD-STD-
2167Al38l. The reader would do well to consult this doc
preparing any software system. E7
Chap. 4 I The Software Life CYcl

chapter' wr
Nevertheless, for some of the documents mentioned in the
The approachtake
discusstechniquesneededspecifically for real-time systems.
of military avionics system
reflects the author's backgroundin the development
other approachesmay, of course, be preferred'

LIFECYCLE
4.1 PHASESOF THESOFTWARE

Thelifecycleofasoftwareprojecthasbeenpartitionedinseveraldiffe
waterfallmodelsl|1,|231,t68].Ttretermwaterfal/isusedtodescri
product occu
idealized notion that each stageor phasein the life of a software
phases clearly defined' we use tl
in time sequence,with the boundariesbetween
throughout the tex
idealized waterfall model similar to the one given in [63]
changesthat are nr
Later on we add modifications to take into accountthe state
relatedto time sequencing.
Tobegin,weconsiderasoftwareproducttobeinthefollowingpha
time order, during its lifetime:

1 . Concept Phase
2. RequirementsPhase
a
Design phase
4 . Programming Phase
5 . Test phase
6 . MaintenancePhase.

of the concepta
This breakdowndiffers from Howden [68] in the addition
test phases.Table 4.1 depictseachphaseand its main byproducts'
in some detail'
The next sectionsdiscusseach phase and their activities
software life cyr
particular, we examine some of the activities over the
most practical. Pamas recognizestl
suggestedby Pamas[124], for they are the
the activities that i
in-t|e real world, the software life cycle and many of
is, of course,due
supposedto occur during it cannot be followed strictly. This

TABLE 4.1 Phasesof the Software Life Cycle, Their Activities'


andTheir BYProducts
Activity Output

White paper
Concept Define project goals
Decide what the Product must do RequirementsDocun
Requirements
Design Document
Design Show how the product will meet the requirements
Build the sYstem Program code
Code
Test reports
Test Check if the system meets the requirements
Maintain sYstem Maintenance reports
Maintenance
Sec.4.1 I Phasesof the SoftwareLife Cycle

the realitiesof budget,time, shifting customerrequirements,and so forth. In short,


this model is simply an abstraction.But Parnassuggeststhat after the project has
beencompleted,tested,and delivered,userscan "cover their tracks"by rnodifying
the documentationso that it appearsthat a formal methodology was followed. The
benefit of this modificationis that a traceablehistory is establishedbetweeneach
program feature and the custornerrequirement dictating it. This promotes a
maintainable,robust,and reliableproduct.Hencewhen the activitiessuggestedin
the following sections cannotbe followed strictly, they should be "faked" over the
life of the project.

4.1.1ConceptPhase
The conceptphaseincludesdeterminationof softu'areproject need and overall
goals. This phase is often driven by managementdirective, customer input,
technologychanges,and marketingdecisions.At the onsetof the conceptphase,
no formal requirementsare written, generally no decisions about hardware/
software environments are made, and budgets and schedulescannot be set. In
otherwords,only the featuresof the softrvareproductand the feasibilityof testing
them are discussed.Usually, no documentationother than internal feasibility
studies,white papers,or memos are generated'
NOTE 4.1 This is not always true. For example,for larger DoD systems,
the user agencydevelopsan "operationalconceptdocument."
Other authorshave not d'efinedthis phasebecauseit was either included in the
requirements phase or not thought to be part of the software project at all.
Nonetheless,the conceptphaseis indeeda bona-fide stagein any softwareproject.
In short, the purpose of the concept phase is to

r Identify product need and goals.


r Producefeasibilitv studies.

Phase
1.2 Requirements
The requirementsphaseis the point at which ideasare committed to paper,usually
as a requirementsdocument or software specification.This document is prepared
by the Customer.(The "customer" could be an actual customer,your boss, the
instmctor of your class, and so forth.) The requirementsdocument contains
specific information about what the software product is to do: timing/throughput
(in real-timesystems),user interface,accuracyrequirements,and so on. Usually,
little or no information on how these requirementsare to be met is dictated, but
schedule and budget are often stipulated. Finally, all interfaces to existing
software and hardware are clearly defined.
From a testing perspective,it is at this point that test requirementsare
determinedand cornmitted to a formal test plan. The test plan is used as the
90 Chap. 4 I The SoftwareLife Cycle

blueprint for the creation of test casesused in the testing phase. (Testing is
discussedmore fully in Chapter11.)
The requirementsphasecan and often doesoccurin parallelwith the concept
phase,and as mentionedbefbre,mosl authorssimply combinethe two. It can be
arguedthat the two are separatebecausethe requirementsgeneratedduring the
concept phase are not birrding, whereasthose determinedin the requirements
phaseare. This differenceis also important from a testingperspective.

4.1.2.1 Functional Requirements The requirementsdocumentincludes


specific information aboutfunctional requirements-those systemfeaturesthat
can be directly testedby executingthe program.

I EXAMPLE 4.1
The following text describesa functionai requirementfor an aircraft navigation system.
"Within 1 millisecond of issuanceof the level l, high-priority interrupt, the navigation
subsystemshall make available all compensatedaccelerationdata to the main computer,which
will read it via DMA. This data cannot be updated while the main computer is in the process
of reading it." I

Other specific functional requirementsinclude systemresponsetimes and


throughputrequirements.

4.1.2.2 Nonfunctional Requirements Nonfunctional requirements Ne


charucterized as system features that cannot easily be tested by program
execution. Nonfunctional requirementsinclude specification of the type of
rnachinethat the systemwill run on, programminglanguageto use, time- and
memory-loading,and version control. Other nonfunctionalrequirementsmight
cover programmingstyle,test conduct,maintainability,modularity,schedule,and
securityof the developmentsite.

4.2
I EXAMPLE
The following excerptfrom the nuclearpower plant systemis a nonfunctionalrequirement.
"The system shall be coded in ANSI-C using acceptedpractices of software engineering.No
'GOTO' statementsare permitted." I

SeeLamb's softwareengineeringtext [88] for a nice breakdownof functional


requirements,goals,and implementationconstraints(hardwareconsiderations).
The following, then, are the chief goals of this phase:

I Define all hardware and softwaie interfaces.


I Write requirementsdocument.
I Write test plan.
T Prepareproject schedule.
I Phasesof the SoftwareLife Cvcle 9l

The requirementsdocumentshould be preparedin accordancewith accepted


standards;for example,DOD-STD-2161A[38] or IEEE standard830 [69]. (These
can be obtained from the Government Printing Office or IEEE, respectively,and
should be part of your engineeringlibrary.)

4.1.2.3 Rules for Requirements and Design Documents When imple-


menting requirementsand design documents,the modeling techniquesused are
not nearly as important as adherenceto the following principles.

1. The documentmust be complete,There shouldbe no holes or gaps.This


goal of writing requirementsand design documentsis the most difficult
to achieve.
2. The documentshould be correct. No laws of physics or interhational
standardsshould be violated. The specified system must be consistent
with the intent of the final deliverable product.
3 . The documentshould be consistent.There should be no intemal conflicts
or contradictions.
A
T. Each requirementor design elementshould be testable.Specifying that a
system should have "reliable performance" is meaninglessbecause it
cannot be objectively tested.Specifying that no faults should be detected
before one hour of operation is meaningful.

Other texts list numerous other criteria, but these are the most reasonable.

DesignPhase
The designphaseis characterizedby the conversionof the requirementsdocument
ro a detailed design specification we call a detailed design document.Preparation
of the detailed design document cannot begin until the requirementshave been
tuIly defined. The design document specifieshow the requirementsare to be met
b1'partitioning the functional features prescribed in the requirementsdocument
into software modules.Techniquesfor doing this arsdiscussedin Chapter 5. The
tbrmat of the detaileddesign document should be in accordancewith an accepted
srandardsuch as DOD-STD-2I67 A [38] or IEEE standard 1016[72]. Adherence
tn a strict design procedure is, of course,important for all software systems,but
particularly for real-time systems.
Concurrent with the preparationof the design document, a set of test cases
basedon the test plan are developed.That is, the requirementsdocument is to the
&sign document as the test plan is to the test cases.Techniquesfor developing
tsft casesare discussedin Chapter 11.
Often it is in the designphasethat problemsin the requirementsdocumentare
iiemdfied. These problems may include conflicts, redundancies,or requirements
ChaP' 4 I The SoftwareLife CYcle
gZ

Usually,problemssuchastheserequire
that cannotbe met wlth currenttechnology.
the granting of exemptionsfrom the
changesto the requirementsdocumenior
must be approvedby the group that
requirementsin question.Such modifications
originallyg"n",u,"dtherequirementsdocument.Inanycase'theprob
resolutionshowsupaSaspecificdirectiveinthedesigndocurnent'
thg system:partitioning into
Two majorui"p, ur" involved in partitioning
partitioningthe software'Discussionof
hardwareand softwarecomponents,ani
but discussionof the secondis of
the first step is beyondthe scopeof thisiext,
great importanceto our Purposes'
To summarizethe tasksof the designphase:

r Partition software into modules'


r Preparedetaileddesigndocument'
r DeveloPtest cases'

4.l.3.lParnasPartitioningPartitioningthesoftwareintomodulesi
governedbyasetofrulesgivenbyDavidParnas[l25landinfactareof
technique,a list of difficult design
referred to as Parnas partitioning. in this
is prepared. Modules are then
decisions or things that are likeiy to change
.,hide,,the eventuai implementationof each design decision or
designatedto
only the function of the module is
feature from the rest of the system. ihus,
implementation.Changesin these
visibld to other modules,not the method of
modulesarethereforenotlikelytoaffecttherestofthesystem.

4.3
I EXAMPLE
TounderstandPamaspartitioning,considerwritingamoduletoimplementanabstractdatat
pUSH and PoP. The implementation of this module should
called a srcct with urro.iut.a op"l*tions procedure witt
item should be passed to the PUSH
be hidden from all .atting moiutes. A data should return a data iten
Similarly, the PoP procedure
assurancethat it will u. pii."a on the stack. via any means othe
Access to the stack in memory
from the stack and adlust the stack accordingly. I
thanPUSHandPoP(exceptperhapsforinitialization)shouldbeprohibited.

speak at a conference'He ir
I recently had the pleasureof hearing Pamar'
engineering'The following point
still carrying the bannerior sanity in software
were made at his talk:

rsomeaspectsofaSystemarefundamental,whereasothelsarearb
and likelY to change'
rltistheunlikelythings,thearbitrarythings'andthingsthatarelikely
changgthat contain "information"'
and usually require lengthit
r Arbiirary facts are hard to remember
I
descriptions.They hre the sourcesof bomplexity'
1. Begin by characterizingthe likely changes'
change'
2. Estimate the probabilities of each type of
II
t_
5er-. I Phasesof the SoftrvareLife Cvcle 93

Organizethe softwareto confine likely changesto a small amount of


code.
4. Provide an "abstractinterface" that abstractsfrom the difTerences.
5. Implement"objects"that hide changeable datastructures.
Thesestepsreducethe "strength"of intermoduleconnections.
r Strengthof connectionis consistentwith an informationtheoreticview,
but numericalcalculationsare not oractical.

Parnasalso indicatedthat althoughmodulardesignis easy to describein


tertbooks,it is difficult to achieve.He suggestedthat extensivepracticeand
examplesare neededto illustratethe point correctly.
Another exampleof Pamaspartitioningis shown in Figure 4.1. Here a
graphicssystemis shown in heirarchicalform. It consistsof graphicalobjects
rtrees,houses,cars, and so on) that are composedfrom circles and boxes.
Differentobjectscan alsoresidein diff'erent'displaywindows.The implementa-
tion of circlesand boxesis basedon the compositionof line drawingcalls.Thus,
line drawing is the most basic hardware-dependentfunction. Whether the
hardwareis based on pixel, vector, turtle, or other type of graphics does not

Figure 4.1 Pamaspartitioning.


ChaP' 4 I The Software Life CYcle
94

matter;onlythelinedrawingroutineneedstobechanged'Hence'weh
to a single module'
isolatedthe hardwaredependencies

4.1.4 ProgrammingPhase

Havingproposedthesoftwareproductintheconceptphase'definedthepr
and parti.iionedthe software functions in
requiremenr, in it requiremenisphase,
" now wiite the code in what is termed the
the design phase,programmerscan when the design
programming;;; in theory' this phase should.only.begin
phasehascompletelyended.Inpractice,however,thereissomeoverlap-
not detectedin the design phase
is desirable ,iri." p-ur"ms in the requirements
a r e u s u a l l y f l u s h e O o u t d u r i n g p r o g r a m m i n g ' I n a d d i t i form
o n ' t husing
e t e sbatch
ttea
designphasein some
implement,* ,",, casesspecifiedin'the
filesorothertechniques'Thisapproachguu*i.'t""'.theefficacyofthetests
facilitatesrePeattesting'

4.|.4.|ResponsibilitiesTheresponsibilityofthesoftwareengineer(

,fr thisphaseisrownreanddebugthesoftwatemodu]esfoperformasspecifi
the detailed design specificatiJn. Thus, the
software engineer now fills in the
d e t a i l s o m i t t e d i n t h e d e s i g n p h a s e . N u m e r o u s a p p r o a c h e s t o a t t a cThis
pr.ur"* are available,una u"gooadiscussionof
thesecan be found in [20]'
kin

least understood-phase of the


phaseis probably the most Jiscussed-though
softwarelife cYcle.
h,
lli"

phaseendswhen the softwareha


4.L.4.2 Termination The programming
integration testing specifiedby tht
beenintegratedand has successfuitypasseOthe
usually ad hoc testing done by tht
software designers.it i. typ" of iesting is
in the requirementsdocumento
progru.*".s ihemselves,uot it can be specified
the detailed design specification'

of the programmin
4.1.4.3 Software Management The management
phasecanbegreatlyenhancedwithversioncontrolsoftware.Ver.sionco
s o f t w a r e i S a S y s t e m t h a t m a n a g e s t h e a c c e s s t o t h e v a r i o u s c o m p o nth
e
from the software library. Version control preventsmultiple accessto
;il
Samesourcecode,providesmechanismsfortrackingchanges,andpre
system reliability'
version integrity. tn ihe long run, it increasesoverall
various developmentenviror
Many commercial prolucts are available for
provide version control facilities. Uni;
ments, and many standaid environments
code control system (sccs) ft
for example, provides the well-known Source
managementof systemcode'
I Phasesof the Software Life Cvcle 95

I EXAMPLE
4.4
A commercial product called the COHESION environment (available rhrough Digital Equipment
Corporation) provides many of the tools necessaryfor the total managementof the software life
cycle. COHESION runs on a variety of platforms, supportsseveralprogramming languages,and can
target a number of commercially available microprocessors.COHESION apparentlyprovides a total
integrated environment for the development of any type of system, including real-time. It
includes:

r Requirementscapture, analysis, and development tools


r Code generators
r Expert systems
r Editors
r Debuggers
r Systembuilders
I Documentation support services
I Software configuration.

and many more features.Although I have no direct experiencewith this product, I.believe it merits
further investigation. I

In summary,the major accomplishmentsof this phase are

r Write software modules.


r Debug software.
r Develop automatedtest cases.
r Integrate modules.

where appropriate, commercial tools should be used to assist in the


administrationof this phase.

Test Phase
Although ongoing testing is an implicit part of the software developmentprocess,
an explicit testing phase exists as well. The explicit phase begins when the
programming phasehas completely ceased.It is during the explicit testing phase
rh:r *1s software is confrontedwith a formal set of test cases(module and system
hrel) developed in parallel with the software. Acceptance or rejection of the
$ottt*'areis basedon how well it fares against the test set. Chapter ,11discusses
manl' of the techniques used in fornial testing. one technique we have not
dlscussedis that of formal program proving. It was disregardedfor two reasons.
ksa some experts are still skeptical of its viability for a large system, for
ample, [32), [45], and [96]. Second, formal program proving for real-time
ryserns requires the use of methodsincluding temforal iogic or processalgebra,
ttd ot-which are beyond the scopeof this text. The interestedreadercan see[99],
[O-r1. or [13] for a discussionof someof thesemethods.
ChaP' 4 I The SoftwareLife CYcle
96

ThisphaseisrigidlyControlledinthatonlybondedcodeisusedan
(exceptfor the softwaretestspecification
changesto thedocumJntuiionareallowed is
in the tesiingprocedureitself;' The phase
and proceduresdocumentfor an error test requirements
in the software
completedwhen either the'critena established
the criteria forcesthe prolectto reentera
documentare satisfied,or failure to meet
previouspi'u,"1,""Section4.2).Regardlessofthe.outcome,oneormo
reportsarepreparedwhichsummarize-theconductandresultsofthetestin
items'
This ptrase,then, takescare of the following

r Perform sottwarevalidation'
r Preparetest reports'

V a l i d a t i o n h a s b e e n d e f i n e d a S . . A r e w e b u i l d i n g t h e r i g h t pright?"
roduct
verification has been defined as "Are we building the product
whereas
with the correctnessof the requirqments'
This implies that validationis concerned
whereasverificationisconcernedwithadherencetothoserequirements..How
manyindividualsusethesetermsinterchangeably,withoutanylossofmea
This text also discussesthem interchangeably'

Phase
4.1.6Maintenance
Themaintenancephase,whichbeginswhenthesoftwarehasbeenverified
haspasseditstestcrrteria),consistsofproductdeploym.entandQustomersu
ttre software will invari'ably be found and
It is during ttri, pt ur. that problems in due to these
areas for i,,'fro'*..nt idintified. Any changes in -the sdftware
u ,oft*ur",.hange and then performing
sourcesare usually handledby makini
approachis to collecta setof changes
regressiontesting(seeChapter11).AnJher
of changes.Later we discusshow these
and then ,.gr"rri* test alainst the set
with theexisting software,and how
changesare-and shouldte-incorporated
(seechapter 11).The maintenancephase
this fits into the overall testing,,rut"gy
ends when the product is no longer supported'
tasks are completed:
Thus, in the maintenancephasetire fottowlng

r Product dePloYment'
I CustomersupPort'
r Continuing program error correction'

4.2 NONTEMPORALTRANSITIONS
LIFECYCLE
IN THESOFTWARE
Although Figure 4'2 implies that tl
sequence'Pamas statesthat this is t
can occur from anY Phase to ar
nontemporal transitions that make t
Sec 4.2 I NontemporalTransitionsin the SoftwareLife Cycle 97

b
*t I
*d/
^@/ Yu,
\%
.o/
uJ/
q-

Figure 4.2 Some nontemporalphasesin the softwarelife cycle.

Since there are six phasesin the software life cycle, there are a total of
-i = -10transitions from one phase to another. Five of these. however. are
l;.rble to temporal transition.
The nine transitionsfrom the other phasesback to the conceptphase or
ents phaserepresenta "back to the drawing board" effect. That is, new
- xackof sufficienttechnology,or otherfactorsforce reconsideration of the
Furposeor redesign.This leavesus with 16 nontemporaltransitionsto
{-et us discusssome of the transitionsdepictedin Fieure 4.2.
A :msition from the programmingphaseto the designphaserepresentsa
E -::: cannotbe implemeirtedor causesunexpectedperformanceimpact.This
s**-essitates redesign,new requirements,or eliminationof the feature.
Transrrionfrom the testing phaseto the programmingor design phasesis
ffi ixror detectedduring testing. Depending on the severity of the error,
:i:r rgqulls reprogramming,redesign,modification of requirements,or
=liil.-)o of the system goals.
:iree transitions from the maintenancephase to any previous phase
rfie conceptor requirementsphasedo not make sense.Errors detected
6-

ChaP.4 I The SoftwareLife CYcle

d u r i n g m a i n t e n a n c e s h o u l d b e t r e a t e d a S n e w c uentire
s t o msoftware
e r r e q u i rlife
e m cycle'
ents:e
through the
concept phase and tolfow tfre sequence
adjustingonlythose"qot'"ttn'sspecificationsanddesignshavingtodowith
set'
prtbl"*, by running the entire test phases'
from the conceptphaseto other
other nonte-'";;t o""riri"., are for aspects of the
m testtngproof-of-principle
Thesemay representprototyping In the final
or scheduie risks or feasibility'
design rhar represe"i ,."fr.i.ui
developmentp,o".,,,'t.nuyu"desirabletoskipoverthestepsprescribed
process'
normal softwaredevelopment

4.3 THESPIRALMODEL

Analternativelife-cyclemodel,the..spiralmodel,',.SuggestedbyBoe
recognizesthattheboundariesarenotalwaysclearlydefined,northep
is shown in
time sequential' The spiral model
and requirements
progr"rr", from the concept
the feasibility
analysis are used to evaluate
e
used after a developmentplan is
ili 1 frototyping is After. the model behavesessen
1li design uno teris have been deveioped. lhat,
tiallylikeu-*u,",rurrmodel.Theaddedriskprotectionbenefitfromth
extensiveprototyping can'be costly'

System
rqmls
concept

rrrl
Figure 4.3 The spiral software
S:c :14 I Standards 99

4.4 STANDARDS

There are many infonnal standardsfor the developmentof software,but most of


rheseare informal or compan)/specific.Three,however,standout.

{"4.1 DOD-STD-2167A

DOD-STD-2I67,4(or MIL-STD-2167,4)establishes the U.S. Departmentof


Det-euse's (DoD) unifonn requirements for softuaredeveiopment throughoutthe
softwarelif'ecycle.In essence, 216'/A. as it is sometimescalled.specifiesmajor
activitiesin the softwaredevelopmentprocess.definesa set of deliverablesor
Data item Descriptions(DIDs), and prescribes formai auditsand reviews.
2167A viewsthe softwarelife cycle in a waterfallmodel,similarto the one
,re have adoptedfor this text. The phasesof the 2161A model are as follows.

Systemrequirementsanaiysis/design
Softwarerequirementsanalysis
Preliminary design
Detailed design
Coding and ComputerSoftwareUnit (CSU) iesting
ComputerSoftwareComponent(CSC) integrationand testing
ComputerSoftwareConfigurationItem (CSCD testing
Systemintegrationand testing.

Table 4.2 shows a rough correspondence betweenthesephasesand those


=-i: \\e describedin Section 4.4.1. The standardalso allows for nine or more
&;.r:rS?nd reviews at specifiedway points, and seventeenrypesof formal reports
arrj iocumentation.The auditsinclude

T\BLE 4.2 Correspondence BetweenThese 2167,4Life-Cycle


Model of Section4.4.1
Phasesand the Seven-Phase

Phase(s) Section4.1 Phase(s)

51slem requirementsanalysis/design Concept/requirements


S-'if iare requirementsanalysis Concept/requirements
F::liminary design Design
D:rriled design Design
il--r:ra_s
and ComputerSoftwareUnit testing Coding
C,rnputer SoftwareComponentintegrationand testing Testing
,1,::rpurerSoftwareConfigurdtionItem testing Testing
!-. -::m integrationand testing Testing
Chap. 4 I The SoftwareLife CYcle
100

r SoftwareRequirementsReview (SRR)
r SystemDesignReview (SDR)
I SoftwareSpecificationReview (SSR)
r Preliminary Design Review (PDR)
r Critical DesignReview (CDR)
r Test ReadinessReview (TRR)
r FunctionalConfigurationAudit (FCA)
r PhysicalConfigurationAudit (PCA)
r Formal QualificationReview (FQR)

Thedeliveryoftheseitemswithrespecttothe216TAlifecycleissh
Figure4.4.Theformalreportsanddocumentation,whicharelargel
describing,are

r System/SegmentDesign Document (SSDD)


r SoftwareDeveloPmentPlan (SDP)
r SoftwareRequirementsSpecification(SRS)
r InterfaceRequirementsSpecification(IRS)
r InterfaceDesign Document (IDD)
r SoftwareDesign Document(SDD)
r SoftwareProduct Specification(SPS)
r VersionDescriptionDocument (VDD)
r SoftwareTest Plan (STP)
r SoftwareTest DescriPtion(STD)
I SoftwareTest RePort(STR)
r ComputerSystemOperator'sManual (CSOM)
r SoftwareProgrammer'sManual (SPM)
r Firmware SuPPortManual (FSM)
(CRISD)
r ComputerResourcesIntegratedSupportDocument
r Engineering Change Proposal (ECP)
r SpecificationChangeNotice (SCN)

A life cyle is shown in Figt


The delivery of theseitems with respqctto the 216',7

AlthoughintheUnitedStatesmanymission-critical_applicatio
has signific
developedusing 2167A, in its full-blown implementation,2l6',TA
overhead.(ManySystemsareimplementedusingasignificantlysmallers
evenin DoD the stand
the model.)Few non-DoD enterpiisesadopt2167A, and
isbeingpartialtydisplacedbytheIEEE830andlsog000standards.
44 I Standards 101

o o

E E !

! 6

.F a>i E
(I

;b;6- E '
_-o o
o o
g 3 #
I O d
!t.E
U O
;

C)

o
h O
-!E-

a o
o
E
C)

r-
TP
r]e a..l
o

F
6 -
s
t a t
o!
(I
oo
o a

g9 bEe s
d eo h
o
a
= i
tr:
_>:

a
"
= D !

: 9 ;
.==
-/
c
t6
Chap. 4 I The Software Life CYcl
102

o o
Y : i
5 d o
E E

P€
. 4 6
- >
o

q b.E
b.frk
o O -

APE

-o)
6E
og I
o

o
o ciP E 3o I
8eE o
>'
q)
q)
I
o

reH Een
o
e-E '

^ o
l
o z
€F: F b,;
t'6:
E o a
duR 6 E"6
.Eov
!co)
I ".;o
.l-----

e
Ea sr d* $'sE
EEE
ra
n

c
q)

E6 E=' fr
o -
EB
.F--- -- e
9es
*,*''R
s - - -
6
c o
b8
g'= R
= 9 4

o & a

FB -

Ee'*
Erc€
c

E
E
aL
AE H
o* 6-
E
o
@

a
I Standards 103

rso 9000
ISO Standard9000 (InternationalStandardsOrganization)is a generic,worldwide
standardfor quality improvemantthat has taken hold mainly in Europe,but an
increasingnumberof U.S. andAsian companieshavealsoadoptedit. The standard,
which collectivelyis describedin five standards,ISO 9000 throughISO 9004,was
designedto be appliedin a wide variety of manufacturingenvironments.ISO 9001
throughISO 9003 applyto enterprises accordingto the scopeof their activities.ISO
9004andthe ISO 9000-X family aredocumentsthatprovideguidelinesfor specific
applicationsdomains.For softwaredevelopment,ISO 9000-3 is the documentof
interest.Many companiesthat had usedDOD-STD-2167A-type developmentare
switching to ISO 9000 becauseit may be better suited for commercialproduct
development.Even somedefensesoftwareengineeringunits are switchingto ISO
9000 in its military equivalent,MIL-STD-49S.
The ISO standardsareprocess-oriented, "common-sense"practicesthat help
companiescreatea quality environment.The principal areasof quality focus are

1. Managementresponsibility
2. Quality system
3. Contractreview
4. Design confiol
5. Documentand data control
6. Purchasing/controlof customer-suppliedproduct
7. Product identification and traceability
8. Processcontrol
9. Inspectionand testing
i0. Control of inspection,measuring,and test equipment
11. Inspectionand test status
12. Control of nonconforming product
13. Corrective and preventive action
14. Handling, storage,packaging,preservation,and delivery
15. Control of quality records
16. Intemal quality audits
17. Training
18. Servicing
19. Statisticaltechniques.

Focusing on many of these areas, such as iuspectron and testing (for


erample, through code walkthroughs), design control, and product traceability
lhrough a "rational design process") indeed increase the quality of a software
product. However, in order to achieve certification under the ISO standard,
104 Chap 4 I The SoftwareLife Cyc

significant paper trails and overheadare required.These need to be weighe


againstthe clear benefitsof such a program before it is undertaken.
For further inforrnation on ISO 9000, consultt501,1126l or check th
Intemet for ISO interestgroups.

4.4.3 IEEE830
IEEE Standard830-1993containsthe recommendedpracticefor SoftwareDesig
Descriptions (SDDs). The guide is described as a "binding contract amon
designers,programmers,customers,and testers,"and it encompasses differe
design views or paradigmsfor systemdesign.The recommendeddesign vieu
include some combinationof decomposition,dependency,interface,and deta
descriptions.Together with boiler plate front matter, these form a standa
templatefor SDDs as given in Figure 4.6.
Sections I and2 are self-evident;they provide front matter and introducto
material for the SDD. The remainderof the SDD is devotedto the four descriptic
sections.
The first, DecompositionDescription,is used to partition the systemin1
I design entities (using Pamas partitioning, for example).Each design entity
described by its identification, type, purpose, function and subordinat
fil ' Recommended description techniques include structure charts, Warnier-O
$r'
rlttl
1-qr, notation,and naturallanguages.
inl
hr,
The next descriptionsection,Dependency,is a descriptionof relationsh
FM
blrr
among entities and systemresources.The entity attributes include identificatio
Inl type, purpose,dependencies, and resources.Example representationtechniqu
[*,, include structurecharts,dataflow diagrams,petri nets, or statecharts.
h,,l The InterfaceDescriptionsectionprovides a list of everythinga design
'Iri:
programmer,or tester needsto know to use the design entities that make up tl
system.Each systernattributeis recordedalong with its identificaiton,functio
and interfaces. These interfaces are described using a variety of mechanisn
including data dictionaries,parameterlists, or annotatedfile headers.
Finally, the Detail Description section is used to show the internal details r
bach systementity whose attributesinclude identification, processingperforme
and data. Any of the representationtechniquesdiscussedin this chapter can I
used to provide detaileddescriptions.
As a software engineeringstandard,IEEE 830 is incomplete in that it on
specifiesdesign(or requirements)description.Additional guidelinesareneededlr
the other phasesin the softwarelife cycle. Someof theseare discussednext.

4.4.4OtherStandards
Standardizing organizations such as ISO, ACM, IEEE, and others active
promote the development of new standardsand the use and improvefit€nt r
existing standards.A list of standardsoffered through the IEEE includes
Standards 105

Introduct ion
1.1 Purpose
1.2 Scope
1.4 Definitions --l
atru
1^-^"-,.-^
nL I ulry It>

References

Tlaa^mn^cit i^n f)acerinf Inn

? 1 Mndr-1o Docnmn6S:tiO:_

3 . 1 . 1 M o d u l el -
3 . L . 2 M o d u l e2
3 . 2 Concurraent Prccess lei-i-:: on
3.2.i ?:ocess - )escr-p'- -c;--
3 .2 .2 Frocess'2Descr'n1-o . i-
I f n.rf^ ne.nrnn.ition

3.3. i Data Enrity 1 Descriprion


3 . 3 . 2 D a L aE n t i t y 2 D e s c r i p t i o n

D e p e n d e n c yD : s c r i p t i o n
4 . 1 lntermodule Dependencies
4 . 2 InLerprocess Dependencies
4 ? D:*a nonendencies

5. Interface Description
5.1 Module Interface
5 . 1 . 1 M o d u l e1 f)a<nri nt- i nn

5 .1-.2 Module 2 T-)acnri nl- i nn

5.2 Process Interface


'1
5.2.1 Process T-)oqnri nj-
+ y u r v r r
i an

5 . 2 . 2 P r o c e s s? f)aqcr i nt-
+ v g f v f r
i nn

6. n^r -.l I ^!
Design
6 . r Module Detailed Design
5.1.1 Modu]e l- Detail-
6.I.2 Module2 DeLail
6 . 2 Uci Lci U e L c i . . i -l . e C l U e S i g n
' -
o.z.l u a t a E n FL. il LF ,y, 1 r nr e
^ ! - l l
Lal_L
o. z. z uata Encl.ty z ueLa]-l

Figure 4.6 Table of contents for an SDD.


106 Chap. 4 I The Sofiware Life Cyr

1. IEEE Std 610.12.1990,Glossary of Software EngineeringTerm


ology
2. IEEE Std 730-1989,Standardfor Quality AssurancePlans
3. IEEE Std 828-1990,Standardfor configuration ManagementPlans
4. IEEE Std 829-1990,Standardfor Test Documentation
5. IEEE Std 830-1993,Recommended Practicefor softwareRequireme
Specifications
6. IEEE Std 982.1-1988,StandardDictionary of Measuresto Produ
R.eliableSoftware
7. IEEE Std 982.2-1988,Guide for the Use of StandardDictionary
Measuresto ProduceReliable Software
8. IEEE Std 990-1987, RecommendedPractice for Ada as a Progr
Design Language
9. IEEE Std 1002-1987,Standard'Taxonomyfor Software Engineer
Standards
10, IEEE Std 1008-1987,Standardfor SoftwareUnit Testing
11. IEEE Std 1012-1987,Standardfor SoftwareVerificationand Validat
I Plans
12. IEEE Srd 1016-1987,RecommendedPractice for software Des
H Descriptions
ffi;
l'ltt't
l,{ 13. IEEE Std 1028-1988,SoftwareReviewsand Audits
f,l
l|n
Fqrr
14. IEEE Std 1042-1987,Guide to SoftwareConfigurationManageme
tirr
! 15. IEEE Std 1044-1993,StandardClassificationfor SoftwareAnomali
rh.i,
I
Er, 16. IEEE Std 1045-1992,Standardfor SoftwareProductivity lVletrics
h;i 17, IEEE Std 1058.l-I987, Standardfor Software Project Managen
'l,r i
Plans
18. IEEE Std 1059-1993,Guide for software verification and validat
Plans
19. IEEE Std l06l-1992, Standardfor a SoftwareQuality Metrics Mettx
ology
20. IEEE Std 1062-1993,RecommendedPractice for Software Acg
srtron
21. IEEE Std 1063-1987,Standardfor SoftwareUser Documentation
22. IEEE Std 1074-1991,Standardfor Developing Software Life Cy
Processes
23. IEEE Std 1209-1992,RecommendedPracticefor the EvaluationI
Selectionof CASE Tools
24. IEEE Std-1219-1992,Standardfor SoftwareMaintenance
25. IEEE Std 1228-i994, Standardfor SoftwareSafetyPlans
26. IFIEEStd 1298-1992,SoftwareQuality ManagementSystemIEEE !
stem, Part 1: Requirements
Sec.4.5 I Exercises
107

Many of theseare joint standardswith ISo, ACM. and others.All can be


obtainedin a singlevolume[158]. The intent here is not to recommendany of
thesestandards;rather,they provide benchmarksfor softwarelife-cyclepractices.
The decisionto adopt or not to adopt is left to the reader.

4.5 EXERCISES

1. Why is it that only "faking" the rational designprocessis suft-icientfor the real world?
2. Write the PUSH and POP routinesdiscussedin Example J 3 in:
(a) C
(b) FORTRAN
(c) Pascal
(d) Ada
(e) Modula-2
Be sure to employ information-hidingtechniques.
3. Discuss the importanceand purpose of pamas partitioning in the design phase
of the
software life cycle. Does Pamas partitioning make sensefrom a real-time perspectrve'l
4. It has been.inferred that a test life cycle similar to the software life cycle occurs
in
parallel [97]' For eachphasein the software life cycle, name the activities that occur
in the
parallel test life cycle.
5. Redraw Figure 4.2 for the test life cycle phasesyou listed in the previousproblem.
6. Estimate the relative percentageof time spent in each phaseof the software life cycle
for
(a) An organic software system.
(b) A semi-detachedsoftware system.
(c) A nonembeddedrealtime software system.
(d) An embeddedreal-time software svstem.
Justify your estirnates.
7. Estimate the relative percentageof time spent in each phase for the test life cycle
vou
derived in exercise4.
t. Discuss the nontemporal transitions for the phasesof the rest life cycle.
9. A mock-up or prototype of a software systemis often constructedduring the designphase.
What are the benefits of using this.technique?
Real-Time
Specification
and
Design
Techniques

KEY POINTS OF THE CHAPTER

L In the absenceof a rigoroussoftwareengineeringmodel (and sometimes


even in its presence),there is a fuzzy line between specificationand
design.
2. No one specificationor design representationtechniqueis a panacea;
therefore,a combination of techniquesshould be used.The nature of the
correctcombinationdependson the systemand the designer'sintuition,
which is developedthrough experience;hence,practiceis essential.
3. The specificationof temporal behavior is the most difficult, but most
important,aspectof specification/designin a real-timesystem.

In this chapterwe survey the featuresand flaws of various techniquesused in the


specification and design of real-time systems. In particular, we examine
ro.-hniques for generating the software requirements document, which is a
[product of the requirementsphase of the software life cycle, and the design
&r'cument,which is a byproductof the designphase.
Recall the difference between specification and design: specffication,
performed by the customer, tells us what the software is to do (and in what
cnr-ironment it will function), and design, performed by the system analyst or
tsirner, tells us how the software will do it. However, many custgmer
ications are so detailed (including. for example, procedure and variable
s) as to be practically design documents.In other cases the customer
though clear, tell us nothing about how a requirement is to be
(e.g., seeExample 4.1), and thus necessitatethe preparationof a

109
Techniques
Chap. 5 I Real-Time Specificationand Design

Separatedesigndocument'Instillothercases,therequirementsaresovag
customerrnput'
pri.fuO" .yri"* designwithout further
siftware engineering)tools, a
with the advent of GASE (computer-aidert code' If
'un immediatelybe convertedinto
graphicalspecification,fo' t*utpt"' and this is
can serveas a softwaredesign'
properly done, a formal specification
sometimesdoneinpractice.However,weassufilethatbothareneeded,an techniques
say specification'we mean those
purposesof this chapter,when we document) and
requirements
usedin both a gooO,oit*ure specificaiion lsoftware
agooddesign(desrgndocument)'softwaredesignshouidad\retotherule in Chapter4'
modular decomposition -*"0and Pamaspartitioningdiscussed
systems are a rich
The techniqrr., in the specificatioi of real-time
Supersetofthoseusedfornon-real-timesystems.Thus,learninghowtos systems
the ability to specify other types of
real-time sysrems;*t, "rrhan.e howevei' we can only survey someof these
Becauseof the depth of this subject' and Z
Ross's Structured AnalysisU35l
methodologiestrere' For example' these
because the author has not used
notation[152] have been omitted' like these in the
of the use of techniques
techniques'A good discussion the chapte
can be found in[114]. Throughout
specificationorr"ut-tii.,.:;;;-
,ti theinterestea'"uo".i,,eferredtomoledetaileddiscussionsondifferentfo
specification techniques'
f,il, It is importanr'iiur *" preface
rhe survey with the following observation
Hi
ttt ;ev. rnethof uuuilubl" for formai
specification it
Almost without are inherentll
rnrs is mostly becauselarge systems
!sl
I "..;;;;,
\4,, unwieldy for large ;;:;
Htl complex.Bur we.Jivpi""ilv dealing*iih large real-timesystems.'That:_lij
u
systeminto smaller componentsystems
\r, the only recourseis to bieak the larger
L ;r
ly';,t somefashion-andtheprefenedmethodistousetheParnaspartitio
4'
hti.
techniquediscussedin ChaPter th
on Real-Time Systemssponsoredby
, t i , :I

At the Advanced Study Institute


in 1992, a panel of seven world-renowne
North Atlanti. rr"uiiorganisution
and design were asked, "what is the corret
experts on softwarl-"p".iri.urion.
techniqueforspecificationanddesignofreal-timesystems?',sevendif
answers*"r*giu"n'-tf'"'"experts'opinionsonlyreinforcedthebeliefthat advanc
.,silver bullet,, exists for specification of real-time systems.Although
you should use those techniques th
have been ,,'ud" ,in"* it " os" of flowcharts,
work for You.

5.1 NATURALLANGUAGES

Naturallanguages,suchasEnglish,arerequiredinthespecificationofsof
documentotherwi
to write a r-ecluirements
systems,for iiivoutd be impossiule
Butnatulallanguagesshouldbeusedonlytoprovideredundantdescriptio
means'
featuresthat are describedby other
Sec. 5.2 I MathematicalSpecification 111

We have been using the English languagethrou-ehoutthis text to describe


real-time systemssince we have not developedthe other tools"For example,in
Chapter1 we talked about the nuclearplant, the avionicssystem,and the airline
reservationsystem.For later use, let us consideranotherreal-time svstem.

. EXAMPLE
5.1
An autornobilesimulator consistsof a steering,braking, display. and accelerationsystem.Each
system executes sporadically except for the display system, which executes every 100

The steeringsystemis initiated when the driver tums the u'heel by an angle, 0, where 0 is
greaterthan --?0 degreesand less than 30 degrees.The positronof the automobilewith respectto
the x, -yplane changesin the r direction by a quantity that is the product of the velocity at time /,
the time in which the wheel is tumed, and the cosineof the angle in which the wheel is tumed.
The position changesin the y directionin a similar mannerexceptthe sineof the wheel angle
is used.
The velocity of the vehicle at any time r is its accelerationat that instant times the time. The
accelerationat any instant is the accelerationdue to pressing the acceleratorpedal for a fixed time
minus the deceleration due ro pressing the brake for a fixed time. Both the acceleration and
decelerationfactors are constant and positive. I

The descriptionin Example -5.1is ambiguousat worst and tediousat best.


Clearly, using any natural languagealone is insufficient to describethe behavior
of complex systems.
In summary, natural languagescan be used to describe systems that are
ertremely simple; to enhanceor amplify descriptionsprovided by other means;or
to bring attention to some subtle point in the requirements.But natural languages
are inherently ambiguous,and no mechanismexists that producesrunnable code
tiom a program specificationwritten entirely in English, for example.Thus, every
nontrivial feature of the systemneedsto be describedby some meansin addition
to naturallanguage.

IATH EMATICAL FICATION


SPECI

T'[re use of mathematics in the specification of software is well understood.


-\lathematics, when properly used, is precise, unambigrious, and efficient,
.r-lrhough some experts still' challenge mathematical verification for large
-(\srems.Furtherrnore,methodsfor optimization of performancecan be obtained
tiirectly from optimizatian of the underlying mathematical model using formal
nerhods. Finally, formal proof techniques can be applied to software in the
$ilne manner as the underlying mathematics, during the software verification
uad testing process.
Erample 5.2 demonstratesthe power of using mathematics in a formal
Fro::ramdescriptionby recastingExample 5.1.
Chap. 5 I Real-Time Specification and Design Techniques
tl2

5.2
I EXAMPLE
display, and acceleration system' Each
An automobile simulator consists of a steering, braking,
and asynchronously except for the display system, which
system can be executed srmultaneously
executesevery 100 milliseconds'
wheel by an angle 0 € [-30' 30]'
The sreeringsystemis initiated when the driver turns the
to the -:r'y plane changes by
The position of the automobile with respect
Ar = r'(r)Iu cos 0

A) = Y(r)re sin e

where T6 is the time in rvhich the wheel is tumed'


v(t) is given bY
v(t) = ct(t)I

where
a(t) = o (,) - P (0

andct(r)andB(r)aretheaccelerationandbrakingfunctions,respectively,givenby
a (t) = tr7"171

P (t) = BTP(I)
I
tlr A and B are positive constants,and I*(l) and Ip(/) are functions
describing when the acceleratorand
I
brakes are applied and for how lcng'

lnsummary,mathematicsiSpreciseandunambiguous.Itpromot
techniquesand rigorous methodsfor code
ly be used in any nontrivial software
y, not all software engineers are apprG
ing, and mathematicalmodels can becortr
i believe that proofs of mathematicsand ol
dine to a false sense of security in I
mathematicallybased specification'

5.3 FLOWCHARTS

Wehaveallseenexamplesofflowchar/sinvolvinganythingfromtoyasse
instructions to VCR operation'
Standardflowchartsarenot-encouragedforuseinthespecificat
SystemsbecausetheypromotetheunwantedGoTostatement.Thi
such as FORTRA)
coincidencesincethe howchart evolved along ryith languages
andassemblylanguagewhichmakeextensiveuseoftheGoTostatemen

I EXAMPLE5.3
(built-in test software) diagnostic featurti
consider the flowchart in Figure 5.1, depicting a BITS
the programmel to use GOTOs, especially if il
an avionics system. The "yes" paths almost beg -",'"h
language such r"
as BASTC
BASIC or FORTRAN.
FORTRAN' I
progr* is rc Ue written in an unstructured

*--<
Sec. 5.4 I Structure Charts 113

Start

Read status
word

Yes Signal
fail Jre

No

Figure 5.1 Flowchart for BITS feature in Stop


avionics system.

Flowcharts are probably the oldest modeling tool fol softw:re systems,and
are widely understood. For this reason, simple systems can be modeled with
flowcharts.According to Pamas,flowcharts are useful for systemson the order of
5,000 to 10,000 instructions, but are not suitable for systems beyond that
sizelI24l.In multitasking systems,flowcharts can be used to describeeach task
separately,but the interaction between processesis not easily represented,and
temporal behavior cannot be described.Finally, the flowchart often encourages
the undesirableGOTO statement.

CHARTS
STRUCTURE

Srructurecharts or calling trees are a widely used mechanismfor describing the


modular decomposition of a system. In struCturecharts, rectanglesare used to
representprocesses.As you move fiom left to right in the structure chart, it
representsincreasing sequencein execution. Moving from top to bottom along
an1.branch of the structure chart indicates increasing detail. Th6re is no formal
method for indicating conditional branching in the tree, but this is usually left as
-selt-evident" or is indicated in some other ad hoc mannet.A form of structure
chart. however, the Jackson chart, doesdepict conditional branching.
Structurecharts'arefound widely in computerscienceliteratureandelsewhere
in describingsystems.For example,many textbooksusestructurechartsto describe
sgleesred sequencesof chapter study. A company's organization chart or your
fmilv treealsocanbe representedby structurecharts.And more topically, structure
Ghonscan be usedfor the designof World Wide Web pages.
114 Chap. 5 I Real-TimeSpecificationand Design Technique

5.4
r EXAMPLE
Consider a common coffee vending machine that can dispenseregular and decaffeiriatedcoffee with
or without sugarand milk. We can describethe systemusing a structurechart as in Figure 5.2. After
acceptingthe customer'scoins and remitting any change owed, the machine reads the buttons
pressed.Then regular coffee, decaffeinatedcoffee, or tea is dispensed,dependingon the choice.
Next, milk andlor sugar is dispensed T

i
I
il
j|ll

fr,i
s?,,,1
li
l r . 1I
I

v,i
F.,i
}.,'
|.,,i
L,ii
lr'tl
[ , Figure 5.2 Calling tree for coffee dispensing machine.

Notice how the tree enablesus to identify common functions such as the
modulesneededto dispensemilk and sugar.
Siructure charts have been used as long as flowcharts to describe system
f'unctionality, and like. flowcharts, they are useful for very simple systems
Structurecharts have severaladvantages:they clearly identify function execution
sequence; they help to identify recuruion and repeated modules; and they
encouragetop-down design. However, although structure charts form a part of
almost any systernspecification,they are flat in nature and cannot easily be used
to depict conditional branching. Most importantly, structurecharts are not useful
in the description of conculrent systems.
For example, in a system where several conculTentprocessesare running,
you can representeachprocessby its own calling tree. There is, however, no way
to describethe interaction betweenprocessesor to representtemporal behavior in
the system. For this reason, modern usage of structure charts is limited to
functional specificatisn at the most abstractlevel.
Pseudocodeand ProgrammingDesign Languages 115

ANDPROGRAMMING
5.5 PSEUDOCODE
DESIGNLANGUAGES

Program design languages(PDLs) differ slightly trom pseudocode,but we will


treat them in a similar manner.Programdesi-enlanguageis a type of high-order
language that is very abstract; that is. it is detached from the underlying
architectureof the machine on which the sy"stemwill run. PDLs typically can
be input into a compiler and translatedrnto hi-eh-orderlanguages.Pseudocode
is a programming languagewith some simple set of semanticsfor which no
compiler is usually built. Both PDLs and pseudocodeare used to specify
systemsin a mannerthat is closeto actually wnting the code.For example,Ada
has been used as a PDL with some success (see IEEE Std 990-1987,
RecommendedPractice for Ada as a Program Design Language). In other
words, formal requirements have been written in Ada and then translated
directly into code. Other Pascal-likelanguagessuch as Sparks[67] have been
used as either pseudocodeor PDL.

I EXAMPLE5.5
Considet the following pseudocodedescribing an automatic teller machine. The pseudocodeis not
a standardone, but its Pascal-like format should render it understandable.

begin
Accept the card
Display "Please enter Your code"
If code not correct
begin
Display " sorrY"
Exit/Eject card
end
ef se
begin
Display "Press Key"
Accept function keY
If key=query account
begin
Display bal-ance
Exit/Eject card
end
el se
begin
if key=withdraw
begin
Display "amount?"
' Accept amount
Chap. 5 I Real-Time Specification and Desip

if amount > balance


begin
Display "sorry"
Exit/Eject card
end
end
el se
begin
Remit cash
Exit,/E j ect card
end
end
efse
beqirr
if key=deposit
begin
Dj-splay " amount ? "
AUUCIJL
^^^^- it
Ue}rv-

Exit/Eject card
end
el-se
begin
Display "lllegal Function"
Exit/Eject card
end
end

The chief advantage of pseudocode and PDLs is that they are nrq
abstract than writing specifications directly in high-order languages.Yet th
afe closer to plogramming language than any method we have seen thus fi
Hence, specifications written in PDLs or pseudocodecan often be translat
into proglams. Languages such as Ada and Modula-2, which have been usr
as PDLs, can certainly handle conculrent specifications, and this rates as I
important advantage.Finally, PDLs and pseudocodeadapt themselvesto form
program-proving techniques rnore easily than unstructured techniques such i
pictures or English.
On the negative side, it should be clear that a PDL is just another kir
of programming languagein which the user must be fluent. In addition, the u
of higher-level abstractionsin no way guaranteesthat errors cannot be mad
and often these errors are more subtle than programming errors. Finally' tl
additional cost and maintenance of these progftlm design tools are oftr
significant.
Sec. 5.6 I Finite StateAutomata tt7

5.6 FINITESTATEAUTOMATA
Finite state automata (FSA) or rtnirc sMrc machines (FSMs) are a type of
mathematicalmodel used in th'e design of compilers, hard-wired logic, and
communication systems, among other places. We have seen a finite state
automatonin Figure4.1.
Intuitively, finite stateautomatarely on the fact that many systemscan be
representedby a fixed number of unique states.The systemmay changestate
dependingon time or the occurrenceof specificevents-a fact that is reflectedin
the automaton.
There are three methodsfor representingfinite stateautomata.

1. Set theoreticmethod.
2. Diagrammaticmethod.
3. Matrix representationmethod.

We presentonly the secondtwo. The formal mathematicalspecificationcan be


found in [3-|,[40], and elsewhere.
There are actually two kinds of FSA, although these are mathernatically
equivalent[3]. Firstly a Moorefinite stateautomatonconsistsof a nonempty,finite
setof statesdepictedaslabeledcircles,oneof which is theinitial state(markedwith
an arrow) and one or more are terminal states(marked with "halos"). An alphabet
of symbolsis given, and a transitionfunction-depicted by labelednlgs-sh6wg
how given a currentstateand symbol,a new stateis entered.
The Moore machinedoesnot allow for outputsduring transition,but output is
provided for by the processesrepresentedby states.Outputs during transition are
allowed,however.by a variationof the Moore machinecalleda MealyFSA.

T EXAMPLE
5.6
Consider a Moore FSA, l,t, to detect even parity in a stream of bits, where stateA correspondsto
an even number of ls, while B correspondsto an odd number of ls. It is descilbed pictorially in
Figure 5.3 and by its matrix representationin Table 5.1 T

l'igurg 5.3 Finite state automaton for even paritv checker.


Chap. 5 I Real-Time Specification and Design Tec

TABLE 5.1 Transition Table for Even Parity


Checker

Current State

Input

0
I

5.7
T EXAMPLE
Next, consider the Mealy FSA, ,t1.,to detect odd parity in a stream of bits. It is describedpictorial5r
in Figure 5.4, and by its matrix representationin Table 5.2. I

1/ "odd"

Figure 5.4 Mealy tinite stateautomatonfor odd parity checker.

TABLE 5.2 TransitionTablefor Odd Parity


Checker

CurrentState

Input

0 A,/"odd" B/"even"
1 B/"even" A/"odd"

I EXAMPLE5.8
a MealyFSAto describe
Finally,consider theautomatic tellermachine in Example5.5.A partia
is givenin Table5.3,andthestatediagram
matrixdescription is givenin Figure5.5. I

In summary,FSAs are widely used in the specification of systemsthat are


state driven For exarnple, lexical analyzers and other language recognition and
translation programs can be easily written using FSAs.
Sdc. 5.6 I Finite State Automata 119

o
o

te s a i

t r v
6 ;

+, .9.
zt
L.9
EE
=6)
oln ra
o" ra

EO
DA Chap. 5 I Real-Time Specification and Design Techniques

TABLE 5.3 Partial Transition Table for Automatic Teller Machine

Input

Wrong PIN # 0/"sorry" NA NA NA


Correct Pin # B/"selection?' NA NA NA
Withdraw NA C/"amount?" NA NA
Query NA E NA NA
Deposit NA D/"amount?" NA NA
Valid $ NA NA F G
Invalid $ NA NA 0 0

Here NA means not allowed.

FSAs are easyto develop,and code can be easily generatedusing tablesto


reprcsentthe transitions between states.They are also unambiguous,since they
can be represented with a formal mathematical description. In addition,

jt concurrencycan be depictedby using multiple FSAs.


Finally, becausemathematicaltechniquesfor reducing the number of states
exist, programs based on FSAs can be formally optimized. A rich theory
surrounds FSAs, and this can be exploited in the development of system
specifications.
on the other hand, the major disadvantageof FSAs is that "insideness"of
modulescannotbe depicted.That is, there is no way to indicate how functions can
be broken down into subfunctions.
In addition, intertask communicationfor multiple FSAs is difficult to depict.
although,an interestingpaper[25] discuSsesa modification of the FSM model
that accountsfor intertask communication and synchronization.Finally, depend-
ing on the system and alphabetused, the number of statescan grow very large.

DIAGRAMS
5.7 DATAFLOW

Dataflow diagrams,proposedby DeMarco[31], are usedas a structuredanalysis


tool for modeling software systems.Extensionsto the original model, given by-
Hatley and Pribhai [62], permit real-time systemsto be modeled.
Starting with the functional requirements of the system, we analyze the
dataflow through the system and determine the major functions. The dataflor
diagramsare developedand decomposedto sufficient depth to identify the majr
componentsof each systemand subsystem.
Having identified ail the functions in the system,and the dataflow betwetn
them, we can then identify concr[rency. Processesthat feed from separatesorum
are consideredto function concurrently.
Some of the conventionsused in the constructionof dataflow diagramsat
given in Figure 5.6. Circles representprocessesor procedures,parallel lines deplr
>e.. 5.7 I Dataflow Diasrams t2l

-.___r_+

Process Sink or source Datastore Dataflow

Figure 5.6 Dataflow diagramconventions.

data storageareas,and squaresrepresentproducersor consumersof data suchas


hardwaredevices.Directed arcs are used to indicate the unidirectionalflow of
data between the componentsof the graph.

.1 DeMarco'sRules
DeMarco[30] has given a set of rules for the constructionof dataflow diagrams,
which are summarizedhere.

1. Identify all net input and output flows. Draw them in aroundthe outside
of your diagram.
2. Work your way from inputs to outputs,backward from outputs to inputs,
or from the middle out.
3. Label all the interface dataflows carefully.
4."Label processesin terms of their inputs and outputs.
5. Ignore initialization and termination.
6. Omit details of trivial error paths (initially).
7. Do not show flow-of-control or control information.
8. Be preparedto start over.

Once an overall dataflow diagram has been drawn, further detail within the
processblobs is provided. The diagram is then redrawn with the additional detail.
This processis called leveling.

f EXAMPLE
5.9
C..rsider an avionics system that collects accelerometerdata every 5 milliseconds and gyro data
*r er1 ,l0 milliseconds, and compensatesboth data at 40 milliseconds to obtain position. In addition,
fue gpos are torqued basedon the compensatedaccelerometerand gyro data every 40 milliseconds,
rir a display is updated based on position every second.Figure 5.7 describesthe system using a
'+mflow diaeram. I

I EXAMPLE
5.10
The development of a loadable progirm from sourcecode is illustrated with a dataflow diagram in
f.qwe 5.8. looking from the left of the diagram to the right, we see that the source code is input
frruana flle to the languagecompiler- Errors are logged to the screenor to a file, while the assembly
h1age code is storedin a separatefile. This file can be submittedto an assembler,which produces
l@en code and logs any errors to the screenor a file. The object code is then presentedto the linker,
rfuih generatesthe loadable program and logs any errors or diagnostics. I
t22 Chap. 5 I Real-Time Specification and Design Technique

bo

b0

'
F

lC
c)
(6 F
u, ra
c
o
ct €,)
E oo
o
o

I
o
o
o
f
o-
o
o
E
o
o
t @
t o
l o
l(s
Sec.5.7 I DataflowDiagrams 123

,;
a.)

0.)
C)
o
I

ilFt
't-
,l(E
F

bo

le tllgl
t :

g€l
" l I
I

t
I
I
r
E
F


H

bo
E
B

(t
o\
ro
3 c)
oo


ra
E
o0
l-

Chap. 5 I Real-Time Specification and Design Techniques


124

5.11
I EXAMPLE
5.9, describing the nuclear plant first
As a final example, consider the dataflow diagram in Figure
Looking from left to right, we seehow discrete signalsflom the temperature
introduced in Chapter 1.
monitored and displayed, and can triggel a shutdown. In addition, discrete signals from
sensorare
the system to alert a police force' I
security sensorsare monitored and displayed,and can cause

5.7.2 Hatleyand Pribhai'sExtensions


in order to render
Hatley and Pribhai have extendedthe dataflow diagram model
include the
it more suitable to the real-time environmentl62]' These extensions
control flow
incorporation of two other types of system representations-the
addition to response time specification
diagram and control specificaiions-in
and a data dictionary.
the flow
The control ftiw diagram is atype of dataflow diagram that shows
lepresentdiscrete
of control signals through the system.Thesecontrol signalscan
sensors,but can also include timing information
signal data irom switches and
and control flow diagram then mesh
from discrete clocks. The dataflow diagram
it should happen'
to describe what is supposedto happen to the data and when
in diagram-
The control speiffications consist of .a finite state automaton
'matic and matrix representation.The control signals in the control flow diagram
the stateof th
representthe alphablt of this machine,whereasthe statesrepresent
to a differer
,yrt"- at that particular moment. Each state can be referenced
dataflow diagram.
Thisschemeisrathercomplicatedand,onthewhole,maybeunsuitable
is left to the reafer'
large and difficult systems.The investigation of this technique
diagrams. Dataflor
Let us ,utnrnurir" the features and flaws of dataflow
data, deemphasia
diagrams have the following features:they emphasizeflow of
identifying conculrency. In fact, in the absence
flow-of-control, and are useful in
automata. In addition, structure
of concurrency,dataflow diagramsare finite state
design process
charts can be ierived from dataflow diagramsto assistin the [30[
can be used to partition a system into hardware ad
Finally, dataflow diagrams
software comPonents'
is tH
The only major weaknessthat seemsto be inherentin dataflow diagrams
it is difficult to shorr
they make it Oimcutt to depict synchronizationin flow That is,
theiype of broadcastcommunicationwe will discusswhen examining statechalts
" usa
in uny case, dataflow diagrams are well understood and widely
some of the other techniques
Dataflow diagrams are usually combined with
yield a coherent software requirementsdocument'

5.8 PETRINETS
petri nets are anothertype of mathematicalmodel usedto specify the operatiom
but they can d
-beperformed in a muliiprocessingor multitasking environment,
>e:. 5.8 | Petri Nets L25

be describedgraphically.A seriesof circular blobs called "places" are used to


representdata stores or processes.Rectangularboxes are used to represent
transitionsor operations.The processes andtransitionsarelabeledwith a datacount
andtransitionfunction,respectively,and areconnectedby unidirectionalarcs.
The initial graph is labeled with markings given by *o rvhich representthe
initial data count in the processes.New markings are the result of the firing of
transitions.A transition,t,fires if it has as many inputs as requnedfor output.
In Petri nets, the graph topology does not change over tirrre; only the
"markings" or contentsof the places do. The system advancesas transitions
"fire." To illustratethe notion of "firing," considerthe Petri nets _sivenin Figure
5.10 and Figure5.11,with associated firing table given in Table5.;i.

Transition1

(b)

Figure 5.10 (a) Typical Petri net and (b) frring a typical Petri net.

TABLE 5.4 Firine Table for Petri Net

P1 P2 r1 D
' A

lno 1 1 2 0
l7l1 0 0 J I
t/|2 0 0 2 2
ll13 0 0 I 3
lllt 0 0 0 A
Chap.5 I Real-TimeSpecifrcationand DesignTechniques
tzl

While
loop

Figure 5.12 Flowchartanalogsto Petrinets.

Peffi nets can be used to model systems and to analyze timing constraints
d race conditions [76], [11]. Certain Petri net subnetworkscan model familiar
&*'chart constructs.Figure 5.12 illustrates these analogies.To further illustrate
fre use of Petri nets in the specification of systems, consider the following
cra.mples.
Chap. 5 I Real-Time Specification and Design Techniques

ga
c.--
ga
C.-.
oa
o
Sec. 5.9 I Warnier-Orr Notation t29

I EXAMPLE
5.12
Considerthe following identity from complexalgebrawhich is usedfrequentlyin many engineering
applications.

\o + bi)(a + bil = a: - b: + 2,tbi


This can be implementedwith the Petri net in Figure 5 1,1.uith correspondinefiring Table 5.5. I

TABLE 5.5 Firine Table for Complex Arithmetic Example

t
D
l P2 P3 P4 ' ) D
I . a

lns J I J 0 U 0 0
lfll 0 0 0 I i 1 0
m2 0 0 0 0 0 0 I

I EXAMPLE
5.13
Consider a Petri net representationfor a hospital's patient monitoring system. Each patient is
connected to machines monitoring blood pressure,heart rate, and EKG. These machines issue a
Boolean signal indicating a FAIL or NO FAIL condition. The results of each of these machines are
ORd together to form a signal called ALARM. The ALARM signals for each of the rooms (one
patient per room) are then ORd together and sent to the nurse's station. If any machine on any
patient indicates a failure, the emergency alarm is sounded and the nurse is directed to the
appropriate patient and machine.
The diagramfor such a systemis given in Figure 5.14. I

Petri nets are excellent for representing multiprocessing and multi-


programmingsystems[76], especiallywhere the functions are simple. Because
they are rnathematicalin nature, techniquesfor optimization and formal program-
proving can be employed.But Petri nets can be overkill if the systemis too simple.
Similarly,if the systemis highly complex,timing can becomeobscured.

WARNIER.ORR
NOTATION

Wamier-Orr notation or Warnier-Orr semanticsis a representationmethodology


that is similar to structurecharts,with severalimprovementsll2Zl, [161]. First, it
can be used to representboth data stnlctures and processes,whereas structure
chartscan be usedto representonly the processes. Second,it usesa more rigorous
set theoreticnotation. In this casewe use setswith the right curly brace, ) omitted
to representprocesses.We use sets within sets to describe increasing detail of
functionality. The ordering of the el.ementswithin the set depicts the order of
execution. The symbol @ representsan "exclusive or," and + representsan
"inclusive or."
Chap. 5 I Real-Time Specification and Design Techniques

gt

>l

t
ra
€J

EO
f-

= c
o
'o
4.
6
f G
5.9 I Wamier-Orr Notation 131

Thus, sequenceis depictedfrom top to bottom, while increasingdetail is


depictedfrom left to right. Note that this is just a variation of structurechans
(mirror image is rotated 90 degrees).Finally, unlike structurecharts,Wamier-Orr
notation provides for looping and conditional constructsthat can be used [o
synchronizemultiple processes.

I E X A M P L E5 . 1 4
A processconsisting of a seriesof modulesmightbe described
in thefollowingway:

r
1 llxii:i
stee
I s t e ol . A . t
| "'praz
t
step1.C
progfam step2
step3.A
*t"p3 I step3.8
t step3.C

The sequenceof operationsfor this systemwould be step l, step I .A, step l.A. ! ^ step 1.A,2,
LB, step 1.C, step2, step3, step3.A, step3.8, step3.C. I

We can depict modifications in the flow-of-control with the following


Jonstructs.In eachcase,"statement"is consideredto be either a singlestatement
t-rr a list of statements,and "condition" is a simple or compound Boolean
;ondition.
The if-then construct is representedas

arbitrarylabei { condition? {steps

*l'lere "condition" is the conditionto be testedand "steps" are the actionsto be


-ien if the condition is true.

I EXAMPLE5.15
Tlr :ollowing testsbit I of a memory-mapped
locationcalled "BITE." If it is set, an error is
m;i.-ated.

FffE-test[Fii I ofB-ffE-setffi'idfate enor

The if-then-else construct can be representedas

ICondition ltrue action


arbitrary label
I@
[Complementary condition {false action

ItiDtrE ii "condition" is true, then the true action or actions are taken; otherwise the false action or
El'Li are taken. I

! EXAHPLE 5.16
fus case.if a particular sensoris detected as "on," then a call is made ro the police; otherwise
mdication that an intrusion has not been detectedis made.
Chap. 5 I Real-Time Specification and Design Techniq

on {call Police
fsensor
intruder detect I O
[sensoroff {indicate all clear

A while loop can be indicated as follows'

arbitrary Iabel (condition,W) lstatement

The statementor statementsare executeduntil "condition" is not true. It should be noted that unl
the condition is actually changed by the statementor an outside event, the loop is infinite.

5.17
T EXAMPLE
Here a polled loop is constructedto check the setting of a particular flag. This techniquecan be u
to indicate that data are available for processing,or it can be used to synchronize two concun
processes.

polled loop (flag = 0,W) (check flag

A repeat until loop can be indicated.

arbitrary label (condition,U) {statement

Here the statement or statementsare executed until the condition is true.


before, unless the condition is changedsomehow,the loop is infinite.

5.18
I EXAMPLE
We can simulate the polled loop from the previous example using the repeat until constrrd
follows:

polled loop (flag = l,U) {check flag

5.9.1 IndexedLoop

The indexed loop constructcan be used to specify that a statementor statenE


- is to be performed n times where n > 0.

arbitrary label (n) {statement

T EXAMPLE 5.19
the additionof a list of 100numbers,
Thefollowingspecifies thatn = 0 andir
assuming
initially.

add 100numbersf n = n + n ( i )
[i=l+l

I EXAMPLEs.20 I
we canretumto ourAutomatb
on a "larger"system,
To illustratetheWamier-Onsemantics
machine and describe its function: I
I
Sec,5.10 I Statecharts 133

{remit cash
"Withdraw " {"amount?"
{"sorry"
@
funcdon?
EnterPIN # "Query'' { display balance
@ "amountl"
"Deposit
@ acceptenvelope

wrong { "sorry" T
5.21
I EXAMPLE
In an interesting article [78], the authors show how Wamier-Orr notation can be used to specify
hypermedia, multimedia, and interactive film systems. The following sequence is a high-level
specification for a dubbed foreign movie on digital video and is taken from this article (modified
slightly). Here "@" is used to indicate parallelism.

frame-group-a
vlcleostream 1I ^
I frame-group-b
@
Iorelqn movle scene lmusrc
sound-stream
IO
/n [speech
v
text-stream { subtitle

Coincidentally, the authors also describe an automatic teller machine using the same technique. I

The use of Wamier-Orr notation is encouragedas an alternativeto structure


charts, which we noted were similar but lacked conditional branching. Wamier-
Orr notation clearly identifies function execution sequence,is good for a top-
down design methodology,and helps to identify recursion and repeatedmodules.
In addition, its conditional branching constructs make it viable for use in
multitasking specification.Warnier-Orr notation is a viable altemative to structure
chartsfor describinghierarchicaldecomposition.As this example shows,it also is
an excellent tool for specifying multirnedia systemsincluding World Wide Web
pages.Finally, both data structuresand processspecification can be represented
g'ith the samemechanisms.
The main disadvantage of Wamier-Orr notation, however, is that the
,ciagrams can grow large and complex, and often cryptic. In addition, the
sinchronization of concurrentprocessesusing only flags is restrictive' Finally, it
is not well-known or widelY used'

STATECHARTS

Harel's statecharts[60], [61] combine FSA with dataflow diagrams and a feature
called broadcast communication in a way that can depict synchronous and
es\Tchronousoperations.Statechartscan be describedsuccinctly as
134 Chap. 5 I Real-Time Specification and Design Techniques

statecharts= FSA + depth + orthogonality + broadcastcommunication

Here, FSA is a finite state automaton, depth represents levels of detail,


orthogonality representsseparatetasks,and broadcastcommunicationis a method
for allowing different orthogonal processesto react to the same event. The
statechartresemblesa finite state automaton,and the various componentsof the
statechartare depicted as follows:

l. The FSA is representedin the usual way, capital letters or


descriptive phrasesused to label the states.
2. Depth is representedby the insidenessof states.
3 . Broadcast communications are representedby labeled alrows, in the
sameway as FSAs,
4. Orthogonality is representedby dashedlines separatingstates.
5. Symbolsa, b, . .. , z representeventsthat trigger transitions,in the sarne
way that transitions are representedin FSAs.
6. Small letters within parenthesesrepresentconditions that must be true fm
the transitions to occur.

5.10.1Depth

A main feature of statechartsis its encouragementof top-down design of


module. For example, for any module (representedlike a state in a
increasingdetail is depicted as statesintemal to it. In Figure 5.18, the navi
system is composed of six internal states. Each of these in tum can
decomposedinto appropriatestatesthat representprogram mbdules.Those
can also be decomposed,and so forth. To the programmer,each s.tatewithin a
representsa procedurewithin a procedure.This insidenessis similar to the nesti
levels depicted in Warnier-Orr notation and encouragesthe corect application
information-hiding principles.

5.10.2Orthogonality

Orthogonalifr depicts concurrency in the system for processes.that nn


isolation, called AND states. Orthogonality is represented by dividing
orthogonal componentsby dashedlines. For example, if stateY consistsof
componentsA and D, Y is called the orthogonal product of A and D. If
enteredfrom the outside (without any additional information), then the
and D are entered simultaneouslv. Communication between the AII{D states
I achieved through global memory whereas synchronization can be
I
I
I
through a uniquefeatureof st4techartscalled broadcastcominunication.
I
I
II
I
L-
Sec I Statecharts 135

5.10.3BroadcastCornrnunication

Broadtast communicationis depictedby the transitionof orthogonalstatesbased


on the sameevent.For exarnple,if a navigationsystemswitchesfrom standbyto
readymode,an eventindicatedby an intemrpt can causea statechangein several
processes.
Another unique aspectof broadcastcommunicationis the conceptof the
chain reaction; that is, events can trigger other events. The implementation
follows from the fact that statechartscan be vieu'ed as an extensionof Mealy
machines,and output eventscan be attachedto the tn-sgeringevent. In contrast
with Mealy machines,however, the output is not seen b1' the outside world;
instead,it affectsthe behaviorof an orthogonalcomponent.
For example,in Figure 5.15 supposethereexistsa transitionlabeledeff, and
if event e occursthen event/ is immediatelvactivated.Event/ could in tum
trigger a transactionsuch asflg.T\e length of a chain reactionis the number of
transitionstriggered by the first event. Chain reactionsare assumedto occur
instantaneously.

Figure 5.15 Chain reactionillustration.

In this system,a chain reactionof length 2 will occur when the ef transition
qlf. UfS.

\!'e now examine two examples of the use of statechartsto illustrate the
:-i:ures that make them unique.

5.22
T EXAMPLE
€lc'.:ier a simple systemconsistingof statesA throughD depictedin Figure 5.16. StateD contains
firfr.: -{ and B. State D enters stateA when eventg occurs, or into state B when event p occurs. D
. .ir!a be enteredvia a transition from state C when event h occurs. State B is enteredfrom state
A r^-Er :renl f occurs.Finally, stateC can be enteredfrom stateA if eventg occursand condition
T
Chap. 5 I Real-Time Specification and Design Technique

Figure 5.16 Four-statesYste

T EXAMPLE5.24 .
the text, and provide
Finally, let us retum to the navigation subsystem discussed throughout
r:^--^- f ^ - : + T r i . given
statechartdiagram for it' It is
^ i . , o n iin Figure 5'18'
n F i o r r r e 5 l R I

Harel's statecharts are excellent for representing real-time system


I
becausethey can easily depict concurrency while preserving modularity.
addition, the concePt of broadcast communication allows for easy intertas

Figure 5.17 Ten-statesystem'

-.:+<
I Statecharts
137

40 ms
interrupt
4C
Read and
compensate
gyro data

1 second

Figure 5.18 Navigation subsystemusing statecharts'

Ada or C code[61].

TABLE 5.6 A Summaryof ModelingTechniques

Technique Advantages Disadvantaees

\atural language Widely used; can clarifY Ambiguous; no code generatlon


descriptions
\lathematical Unambiguous; formal methods Can be cryptic: hard to use: training
specification applicable;code oPtimization not widespread; error-Prone
possible
Flor.r'chart Widely used; good for single tasks No concurrency: no temPoral
behavior;encouragesGOTOs

Srucrure chart Widely used; good for small No conditional branching; no


systems; encouragestoP-down concurrency; no temporal
design behavior

Fsudocode and Close to programming language: Costs can be high: error-Prone


PDL formal methods aPPlicable
Widely used; easYto develoP: code "insideness"not depictable;no
Frlte smte
ar,rtomaton generation Possible; code concurrency: number of states
optimization Possible grows

Daaet-low Widely used; concurrency; sFtlcture Synchronization hard to show


Jragram charts can be derived; helPs in
Parnaspartitioning
Chap. 5 I Real-Time Specification and Design Technique

The major drawback of statechartsis that they are not widely used,althoug
this will changeas more designersdiscoverthe benefitsof statecharts.
Table 5.6 summarizessome of the advantagesand disadvantagesof th
modeling techniquesdiscussed.

5.11 SANITY IN USING GRAPHICAL TECHNIQUES

When using any form of graphical technique, be reasonablein laying out you
designs.For example, the depiction in Figure 5.19 is taken from a talk o
complex systemsdesign by Pamas. It is essentiallya statechartshowing th
same design and with the boxes redrawn. The effect is astounding.The mon
is: use aestheticreasoningin drawing design diagrams'

The rightway

The wrong way

Figure 5.19 Graphical design, the right way and the wrong way.
[2 I Exercises 139

EXERCISES

1. Convert the structurechart for the cuffee machine in Example 5.4 into Wamier-Orr
notatlon.
2, Use structurechartsto describethe automobilesimulatorin Example 5.1.
3. Use structurecharts to describethe patientmonitoring s1'stemin Figure 5.i4.
4. Use flowchans to describethe automobilesimulatorin Example 5.1.
5. Use flowchartsto describethe patient monitoring s)'stemin Figure 5 14
6. Build a Moore finite stateautomatonto acceptthe *ords "cab." "cob." "cat." "cot,'but
no othersfrom the alphabett = {a.b. c. r. ol.
7. Build a Moore finite stateautomatonto acceptall w,ordsexcept"cab." ,,cob,".,cat.".,cot"
f r o m t h e a l p h a b et t = l a . b . c . t . o l
8' Build a Mealy finite stateautomatonto describethe coffeemachinein Example5.4. The
machine should output words such as "adding sugar" when appropriate.
9. Design a Moore finite stateautomatonfor the alphabel,1- = [0,1 | which acceptsthe set
of all stringsvith 3 consecutiye
zeros.
10. Research the difference between a deteiministic and nondeterministic finite state
automata.Under what circumstanceswould a nondeterministicfinite stateautomatonbe
usedto specify systemrequirements(i.e., rvhatkinds of systemswould be amenableto
this technique)?
11. In the languageof your choice, write a program which implementsthe finite state
automatondescribedin exercise6. The program should write "accepted"if the word is
recognizedand "rejected" if it is not. Input can be either from the keyboardor a file.
12. Use a Moore finite stateautomatonto describethe BITS processin Figure 5.1.
13. Use Wamier-Orr notation to describe the coffee machine in Example 5.4.
14. Use Warnier-Orrnotation to describethe patient monitoring systemin Figure 5.1.
15. Use a dataflow diagram to describethe coffee machinein Example 5.4.
16, Use a dataflow diagram to describethe patientmonitoring systemin Figure 5.14.
17. Use a dataflow diagram to describethe automobilesimulatorin Example 5"1.
18. Use a Petri net to describethe following
(a) Thediscreteconvolutionof tworealvaluedfunctions/(r)andg(r),
t=0, 1,2,3,4,5.

5
(f * s)G)= lof(i)s(t_i)

(b) The matrix multiplication of two 4 X 4 matrices.


19. Draw a Petri net to perform the quadratic equatlon

-bx\-b2-4ac
)-

Attempt to maximize parallelism.


20. Use a Petri net to describethe coffee machine in Example 5 4
21. Use statechartsto describethe automobilesimulatorin Example -5 1.
22. Use statechartsto describethe patient monitoring srsrem in Fi_eure5 l-t
23, Use statechartsto specify the designof a phone ansuerin_smachine*ith *hich you are
familiar.
Chap. 5 I Real-Time Specification and Design Techniques

24. A real-time system is to be designed which models the human body on a single
processing system.The simulator consists of the following five subsystems:
(a) Cardiovascular system
(b) Digestive system
(c) Neural system
(d) Motor system
(e) Reproductive system
Model the systemusing any combination of the techniquesdiscussedin this chapter.This
is not a test ofphysiology; rather, concentrateon clearly modeling the system using the
Iayperson'sknowledge of how the subsystemswork.
25. Using an appropriatecombination of the techniquesdiscussedin this chapter,model the
operation of an hutomobile. Include a description of the following subsystems:
(a) Steering
(b) Braking
(c) Acceleration
(d) Dashboard display
Don't worry about the equations underlying these systems;a good intuitive description
will do.
26. Use any one of the modeling techniques discussed to model the software life cycle
employing the software test cycle as a stimulus.