11
IEEE TRANSACTIONS ON EDUCATION, VOL. 40, NO. 1, FEBRUARY 1997 1 Emulation of the occam TM Parallel Programming Language Bernard S. Doherty and Steven A. J. Harris Abstract—This paper describes emulation of parallel execution of a program written in standard occam TM source code. The occam language is a high-level language specifically designed to accommodate concurrent programming. The emulator checks and executes most instructions in the occam 2 language, providing a useful tool for debugging simple occam programs, and also provides accessibility to allow monitoring of execution. A “user friendly” graphical interface is an integral part of the emulator. The paper describes the emulator and its use in teaching the occam language and parallel programming concepts to final year undergraduates. The teaching context is given and laboratory notes outlined along with sample programs that illustrate features of the language. I. INTRODUCTION T HIS paper describes an emulator using pseudo-concurrent interpretation of the occam language for use in teaching and development of occam programs. The emulator executes programs written in occam, providing tuitional support for the language and assisting understanding of operation of the occam language, and, with it, aspects of parallel computing. It also provides a tool for debugging simple occam TM programs destined to be run on transputers. The occam language [1] was developed in conjunction with the transputer [2] as a language directly associated with a microprocessor designed, ab initio, to operate in concurrent systems. The occam model of concurrency [1] is based on the concept of communicating sequential processes [3], [4]. The occam language is a RISC language specifically aimed at providing support for concurrency. The language provides constructs to specify whether processes are sequential or parallel, and these constructs determine the temporal relation of the processes. The language also provides specific facilities for handling of time. The full syntax of the language can be found in standard references [1], [5]. Some more specialist aspects of the language are discussed in Appendix I. The emulator accepts properly formatted occam source code, and uses state transition lexical analysis and recursive descent syntax analysis to interpret the source code to an intermediate language that is used to execute the program. Concurrency is emulated by pseudo-concurrent multiple-stack execution of parallel processes. Manuscript received December 31, 1992; revised October 18, 1994. B. S. Doherty is with the Department of Computer Science and Applied Mathematics, Aston University, Aston Triangle, Birmingham, B4 7ET, U.K. S. A. J. Harris is with Wind River Systems (UK) Limited, Aston Science Park, Aston Triangle, Birmingham, B4 7ET, U.K. Publisher Item Identifier S 0018-9359(97)01304-6. The use of emulation in teaching of microprocessors has been described by various authors. Most work has been on conventional von Neumann processors operating singly [6]–[10]. Emulation is described at register and memory level. The systems described in these papers show internal processor operation, at bit level, and are used to enhance teaching of conventional single-processor systems. Emulation of execution of symbolic microprograms and assembly language programs at bit level in microprogrammed systems [11], [12] and bit- level emulation of a bit-slice processor [13] have also been described. Emulation of a multiprocessor system [14] has been used to evaluate performance of a parallel prolog interpreter op- erating under a communicating sequential processes model. A uniprocessor implementation based on an abstract machine that handles process queuing and scheduling has been used to emulate concurrent prolog [15]. Emulation of execution of assembly language on an architecture has been implemented [16] with the C language. An occam development system has been created [17] to accept a subset of occam source code and produces an intermediate code that translates to native Intel 8086 machine code for execution on the IBMPC. An accompanying run- time system provides the necessary support environment [18]. The work described in this paper has the educational spirit of the processor emulation systems [6]–[13], but concerns itself specifically with modeling the execution of the occam language, seeking, unlike previous applications, to shield the user from bit- and register-level considerations to allow focus on parallel programming. Indeed, the work described in this paper seeks to go beyond explanatory or illustrative application and to move toward being a development tool for occam programming. The concurrency emulation method employed makes use of techniques that have occasional similarities to the systems described by Rizzo [14], Houri and Shapiro [15], and Mills et al. [16]. The system described by Macfarlane et al. [17] operates on the principle of translation of occam source to an intermediate language but is then concerned with actual exe- cution of the language rather than with emulation, removing the access to the “working” of the language provided by the emulator described in this paper. The emulator was developed to run on the Apple Macintosh TM computer, with the emulator program written in Pascal. The emulator could readily be translated to another hardware platform. 0018–9359/97$10.00 1997 IEEE

Emulation of the occam(TM) parallel programming language

  • Upload
    saj

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Emulation of the occam(TM) parallel programming language

IEEE TRANSACTIONS ON EDUCATION, VOL. 40, NO. 1, FEBRUARY 1997 1

Emulation of the occamTM ParallelProgramming Language

Bernard S. Doherty and Steven A. J. Harris

Abstract—This paper describes emulation of parallel executionof a program written in standard occamTM source code. Theoccam language is a high-level language specifically designedto accommodate concurrent programming. The emulator checksand executes most instructions in the occam 2 language, providinga useful tool for debugging simple occam programs, and alsoprovides accessibility to allow monitoring of execution. A “userfriendly” graphical interface is an integral part of the emulator.

The paper describes the emulator and its use in teaching theoccam language and parallel programming concepts to final yearundergraduates. The teaching context is given and laboratorynotes outlined along with sample programs that illustrate featuresof the language.

I. INTRODUCTION

T HIS paper describes an emulator using pseudo-concurrentinterpretation of the occam language for use in teaching

and development of occam programs. The emulator executesprograms written in occam, providing tuitional support forthe language and assisting understanding of operation of theoccam language, and, with it, aspects of parallel computing. Italso provides a tool for debugging simple occamTM programsdestined to be run on transputers.

The occam language [1] was developed in conjunction withthe transputer [2] as a language directly associated with amicroprocessor designed,ab initio, to operate in concurrentsystems. The occam model of concurrency [1] is based on theconcept of communicating sequential processes [3], [4].

The occam language is a RISC language specifically aimedat providing support for concurrency. The language providesconstructs to specify whether processes are sequential orparallel, and these constructs determine the temporal relationof the processes. The language also provides specific facilitiesfor handling of time. The full syntax of the language can befound in standard references [1], [5]. Some more specialistaspects of the language are discussed in Appendix I.

The emulator accepts properly formatted occam sourcecode, and uses state transition lexical analysis and recursivedescent syntax analysis to interpret the source code to anintermediate language that is used to execute the program.Concurrency is emulated by pseudo-concurrent multiple-stackexecution of parallel processes.

Manuscript received December 31, 1992; revised October 18, 1994.B. S. Doherty is with the Department of Computer Science and Applied

Mathematics, Aston University, Aston Triangle, Birmingham, B4 7ET, U.K.S. A. J. Harris is with Wind River Systems (UK) Limited, Aston Science

Park, Aston Triangle, Birmingham, B4 7ET, U.K.Publisher Item Identifier S 0018-9359(97)01304-6.

The use of emulation in teaching of microprocessors hasbeen described by various authors. Most work has beenon conventional von Neumann processors operating singly[6]–[10]. Emulation is described at register and memory level.The systems described in these papers show internal processoroperation, at bit level, and are used to enhance teaching ofconventional single-processor systems. Emulation of executionof symbolic microprograms and assembly language programsat bit level in microprogrammed systems [11], [12] and bit-level emulation of a bit-slice processor [13] have also beendescribed.

Emulation of a multiprocessor system [14] has been usedto evaluate performance of a parallel prolog interpreter op-erating under a communicating sequential processes model.A uniprocessor implementation based on an abstract machinethat handles process queuing and scheduling has been usedto emulate concurrent prolog [15]. Emulation of execution ofassembly language on an architecture has been implemented[16] with the C language.

An occam development system has been created [17]to accept a subset of occam source code and produces anintermediate code that translates to native Intel 8086 machinecode for execution on the IBMPC. An accompanying run-time system provides the necessary support environment[18].

The work described in this paper has the educational spiritof the processor emulation systems [6]–[13], but concernsitself specifically with modeling the execution of the occamlanguage, seeking, unlike previous applications, to shield theuser from bit- and register-level considerations to allow focuson parallel programming. Indeed, the work described in thispaper seeks to go beyond explanatory or illustrative applicationand to move toward being a development tool for occamprogramming.

The concurrency emulation method employed makes useof techniques that have occasional similarities to the systemsdescribed by Rizzo [14], Houri and Shapiro [15], and Millset al. [16]. The system described by Macfarlaneet al. [17]operates on the principle of translation of occam source to anintermediate language but is then concerned with actual exe-cution of the language rather than with emulation, removingthe access to the “working” of the language provided by theemulator described in this paper.

The emulator was developed to run on theAppleMacintoshTM computer, with the emulator programwritten in Pascal. The emulator could readily be translatedto another hardware platform.

0018–9359/97$10.00 1997 IEEE

Page 2: Emulation of the occam(TM) parallel programming language

2 IEEE TRANSACTIONS ON EDUCATION, VOL. 40, NO. 1, FEBRUARY 1997

Fig. 1. Functionality of the emulator.

The emulator has been used in teaching the occam pro-gramming language. The teaching context and some examplesof material provided to the students indicate the utility ofthe emulator in teaching. Performance and limitations arediscussed.

II. EMULATOR OVERVIEW

The main functions in the emulator program can be sum-marized by the diagram of Fig. 1.

The emulator is usefully considered in two parts: the analy-sis of the occam source code to produce the intermediate code,and the execution of the intermediate code.

A. occam Source Code Analysis

The input to the emulator is text obeying the programmingconventions of occam [1]. Initial attempts to emulate executionby direct interpretation of source text encountered considerabledifficulties, which were resolved by translating source code toa lower level intermediate code then “executing” this code.Use of intermediate code allows a flexibility of operationwhich proved useful for emulation of parallel processes. Theintermediate code was obtained by recursive descent syntaxanalysis of the occam source text, producing code for a stack-based virtual machine.

B. Execution

The occam model is built on communicating processes,and the emulation must therefore provide for both processesand communication.The concurrent operation is a central partof the language and a mechanism is provided to emulateconcurrency. occam has facilities for external input/outputhandling, and a simple mechanism for this is incorporated inthe emulator.

III. SOURCE INTERPRETATION

Source interpretation is an essential precursor to theactual emulation. The various aspects of source interpre-

tation—Lexical Analysis, Symbol Table, Recursive DescentSyntax Analysis, Expression Evaluation, Input/Output Control,and Error Handling—are interrelated as shown in Fig. 1.

A. Lexical Analysis

The primary task of the lexical analysis is to read inputcharacters and produce a sequence of tokens for the recursivedescent syntax analysis phase which follows. It also performssecondary tasks: removal of surplus spaces; recording thenumber of “end of line” markers, and the number of charactersread from source to allow association of error messages witha particular part of the source; and storing identifiers foundin the text in a symbol table. A finite automaton approach isused to move through the input text and identify tokens usinga transition diagram to model each token.

The lexical analysis is conventional [19] except where itis modified to take account of occam indenting and exdenting(scope in occam is identified by the level of indent and exdent).

B. The Symbol Table

The emulator collects information on a name when it isencountered for the first time and references that informationwhen deciding whether the name is being used legally andwhen allocating “space” during code generation.

C. The Recursive Descent Syntax Analyzer

The RDSA works naturally with context-free grammars[20], and, although the occam grammar is not fully context-free, by using information stored in the symbol table aboutthe current token it is always possible to achieve the correctdecision and continue the syntax analysis. The recursivedescent analysis was based on conventional procedures ([19],[21]) with modifications to accept the special needs of occamarising from the way call and assignment operate in occamand from colon usage in occam.

D. Expression Evaluation

The emulator is able to handle evaluation of the full setof occam expressions. Constant expressions were evaluatedat compile time, while variable expressions are evaluated atrun time. occam expressions are constructed from operands,operators, and parentheses. The operators are conventionalarithmetic and Boolean operators. Bitwise and shift operatorsare provided for bit-level evaluation. For expression evalu-ation, infix ordering of operators is converted to a postfixform.

E. Error Handler

As this is an interactive interpreter, the error handling unitdoes not need to encompass any error recovery. The errorhandler simply reports an error in the translation process tothe user and processing is suspended. The error messagescontain as much information as possible. Almost all of theerrors generate a unique textual error message for the user.

Page 3: Emulation of the occam(TM) parallel programming language

DOHERTY AND HARRIS: EMULATION OF THE occamTM PARALLEL PROGRAMMING LANGUAGE 3

F. Intermediate Code Generation

The intermediate code was generated on the basis of con-ventional stack-based constructs. The code to implement eachof the constructs was incorporated into the RDSA, whichas it analyzes the incoming text generates correspondingintermediate code which is held in a separate code store, alongwith any operands.

The intermediate code is generated for execution on avirtual machine with a von Neumann architecture, using aconventional fetch/execute cycle, and is therefore set out ina linear fashion with appropriate test and jump instructions toimplement the semantics of the various language constructs.

The constructs are defined conventionally [19], [21] using anexecution diagram in combination with informal semantic def-initions, providing easily understood and precise operationaldefinitions that are independent of interpreter language andmachine architecture.

Appendix II shows an example of a small occam programtranslated into intermediate code.

The PAR construct causes insertion of intermediate codeswhose function at run time is to set up the multiple activationrecords that allow the scheduler to emulate parallel operation.At the end of the PAR construct, codes are inserted to removethe activation records once the construct is exited.

IV. EXECUTION OF THE CODE

A. Intermediate Code Interpreter

The interpreter is a virtual machine which executes theintermediate code generated from the translation of the occamprogram described earlier.

The structure of the machine follows a standard von Neu-mann architecture, implementing a sequential operation withopcodes and operands fetched from code store then executed.The interpreter is built on a simple stack-oriented machine.

The hypothetical machine contains a working store (WS)which holds values of runtime variables. Each of the concur-rent processes uses its own stack for expression evaluation,etc.

The interpreter architecture consists of three major areas ofstorage, along with various registers:

The Code Storeholds opcodes and their associated operands.It is referenced by the current value of the Program Countervariable in the emulator. As processes are swapped in and outby the scheduler, the value of the program counter will beupdated to the next instruction to be performed in the newcurrent process.

The Working Storeprovides storage for values of programvariables. Working Store can be addressed directly or by onelevel of indirection using an address held on the top of thestack.

The Stackis central to the operation. Many opcodes usethe stack, especially when carrying out input/output and ex-pression evaluation. Each process that is executing has anindividual stack. The scheduler ensures that the appropriatevalue is stored in the stack pointer variable when the currentprocess is changed.

The current process variable indicates which of the stackpointers, evaluation stacks, and local clock values should beused by the interpreter. The value of the current processvariable will be determined by the scheduler, depending onthe next process to be taken off of the active queue. The valueof the current stack pointer is set during a process contextswitch to the value held in the current process variable.

The interpreter instruction set consists of an operation codefollowed by zero, one, or two operands. Within the code storeinstructions are represented numerically, but for convenienceand ease of understanding the interpreter uses a mnemonicassembly code.

The mnemonics given in the illustrative translation to inter-mediate code in Appendix II give a flavor of the instructionset.

The execution of instructions held in the interpreter codestore is sequential, beginning at the first instruction andcontinuing until the HALT opcode is executed. The fetchingof opcodes and operands from the code store incrementsthe Program Counter by the number of items obtained. Theoperation specified by the opcode is then carried out, the valueof the “CyclesUsed” variable is incremented (for use by thescheduler), the Program Counter adjusted if need be, and thenext opcode and its operands obtained for execution.

Whenever a channel input/output operation or transfer ofcontrol instruction is carried out, the interpreter calls thescheduler.

B. Emulating the occam Model

1) occam Processes:An occam program consists of pro-cesses each of which starts, carries out some actions, thenstops. The processes can operate in parallel. At any time, aprocess can have one of two states: active or inactive. Activeprocesses are processes being executed or being held on theactive list awaiting execution. Inactive processes are processesthat are ready to input, ready to output, or waiting for aspecified time.

2) Implementation of Concurrency Emulation:A parallelconstruct will have an activation record allocated for eachconcurrent process that it specifies. These records are placedin an active queue. The first process in the queue will beexecuted up to the point that either an I/O, “wait,” or “jump”instruction is executed. At this point the scheduler deschedulesthe process and adds it to the bottom of the queue. The nextprocess may then be taken from the queue and executed.When a process stops it is removed from the queue.

3) The Scheduler:The emulation maintains two lists ofprocesses: the first containing active processes; the secondinactive processes. Each list contains relevant process acti-vation records. A process is started by adding it to the end ofthe active list. When the current process is descheduled it isplaced at the end of the list and the new current process istaken from the front of the list.

Descheduling can occur as the result of a process carryingout an I/O operation or an occam “wait” instruction. Processescan also be descheduled when they have exhausted their timeslice. The time slice is calculated from a central clock. The test

Page 4: Emulation of the occam(TM) parallel programming language

4 IEEE TRANSACTIONS ON EDUCATION, VOL. 40, NO. 1, FEBRUARY 1997

to see if the process has exceeded its time slice occurs when ajump instruction is carried out. This prevents a single processfrom “hogging” the processor for more than one loop cycleand consequently stopping other processes from executing.

The act of descheduling a process will require storage ofinformation in its activation record and in this the methodused in the transputer is followed: only workspace pointersand the program counter are saved and these are added to therelevant process queue (by changing the value of a pointer).Using this method context switching is rapid.

4) Communications:Interprocess communications is emu-lated by a technique based on the execution model of an occamprogram running the transputer, except that it utilizes processevaluation stacks to enable information transfer. A “channellink word” register contains the identifier of the channel whichwishes to communicate. This is used to ensure that the samechannel is invoked in both the sending and receiving processes.

A channel link word is allocated when the channel itselfis declared in an occam program. Initially, the channel linkcontains the value zero, which signifies that no processes areready to use the channel. If a process reaches a channel I/Oinstruction, the process pointer (which points to the process’sactivation record) is placed in the channel link word, and theprocess is suspended.

If the outputting process becomes ready first it places thevalues to be transferred on its stack, updates the stack pointer,puts the word count into its activation record, and stores theprocess pointer in the channel word. Then when the inputtingprocess becomes ready it can obtain the process address fromthe channel link word and consequently locate the stack topand find how many words are to be transferred.

If the input process becomes ready first it places its processpointer into the channel link word, clears the word countvariable, and suspends. When the output process becomesready to communicate it can then obtain the process pointerfrom the channel word, which gives access to the appropriateprocess number and stack top pointer. The output process thencopies the values to be output onto the input process stack,updates its stack pointer value, stores the number of wordscopied in the input process’s word count, places the activationrecord back on to the active queue, and clears the channelwordlink.

5) Input–Output: The user input of information to an occamprogram is a little more complicated. This requires that aMacintosh “mini” event loop be set up to repeatedly scanfor user interactions. These interactions fall into two distinctclasses:

• Clicks “on the screen” with the mouse.• Key depressions on the keyboard.

With key depressions, the event is recognized in the eventloop and the character obtained directly from the operatingsystem for return to the calling procedure after checking. Oncea character has been obtained, the event loop is stopped andthe character returned to the occam interpreter for subsequentprocessing.

This mechanism allows user interrupts via the keyboard tosimulate real-time events. The response to an interrupt is to

bring up a window that allows the user to select the notional“source” of the interrupt, to allow testing of various externalinput channels in the program, and also to test time-sensitiveconstructs such as “ALT” and “PRI ALT.”

V. THE USER INTERFACE

The occam emulator runs on an Apple computer andmakes full use of the standard Macintosh

TM

user interface.There are various windows provided: a text input window

to allow the entry of an occam source program; an occaminput/output window, and a report window. Dialog boxes areused for simple messages and control. The full editing and filehandling facilities of a Macintosh application are available.

The text editing procedures are conventional except formodifications to simplify the entry of the indents and ex-dents which are significant in determining scope in an occamprogram.

Text editing has been altered to operate as follows.

• When a carriage return key is depressed the cursor ismoved to the next line directly underneath the firstnonspace character on the preceding line.

• Before text is typed on any given line, depression of thespacebar (backspace) will indent (exdent) the cursor twospaces automatically.

• Any other character is input to the text window as normaluntil carriage return is again depressed, which reactivatesthe indenting facility.

The occam interpreter is accessed by the user through the“occam menu,” which appears on the menu bar at the top ofthe screen when the application is executed. The menu itemsare:

• Syntax Test—Allows the text of the occam program tobe tested for syntax errors.

• Execute—Initiates execution of occam program in textwindow.

• Display Diagnostics—This option invokes procedures todisplay the values of user selected occam variables.

• Show occam Window—Activates the window that isused to interact with the occam program.

• Clear occam WindowSyntax errors are reported in a dialog box, making use of

the error-handling facility in the RDSA to identify errors.Once the source text is entered the program can be “run,”

with, under the finest grain, the result of the execution of eachstep reported, and under the coarsest grain only the existenceof errors of execution, for example deadlock, reported. Reportsare presented in a separate window to the source text, and itis only necessary to swap windows to edit the source text.

VI. THE EMULATOR IN USE

A. Physical Provision

The emulator has been compiled in LightSpeed Pascal(version 4) and tested on various Apple Macintosh computers,and has run reliably. The models on which the emulator

Page 5: Emulation of the occam(TM) parallel programming language

DOHERTY AND HARRIS: EMULATION OF THE occamTM PARALLEL PROGRAMMING LANGUAGE 5

has been tested include MacPlus, MacII, Centris, LC475, andPowerbook. It has also operated successfully from a server.

B. Teaching Context

The emulator is used in the teaching Final Year moduleCS372 “Real-Time Systems Applications.” The teaching timeallocated directly is 30 h over ten weeks, with laboratory timemade available on a free access basis. The module concentrateson real-time environments and real-time software, focusingmore on design methodologies than on implementation details.Speed of response and integrity of software are emphasised.Concurrent systems are outlined, refreshing material frompreviously taught modules. The languages and the hazards ofconcurrent systems are discussed, and exercises provided inboth ADA and occam. occam teaching was previously doneon a real transputer system, but the interface to the systemwas difficult for students to learn in the time available, andas there was only one terminal providing access to the systemthere was a substantial bottleneck in laboratory scheduling.

C. Class Use

The emulator was made available to students on a serverconnected to a laboratory of 16 Apple Macintosh LC475’s.The laboratory is freely accessible over an extended period ofthe day and evening. The program was made available in com-piled form, together with several small sample programs andaccompanying laboratory notes (Appendix III) to supplementthe brief language tuition delivered in lectures.

The emulator was used to support teaching of occam bymeans of sample programs and class exercises for the studentsto complete. The sample programs provided were designedto illustrate particular points, to provide guidance in specialfeatures of occam, and as an example of how to get started.The class exercises were based on relatively small problemsand were presented to the students as work to be completedin their own time, with two of the problems required to besubmitted as assessed coursework. Illustrative questions aregiven in Appendix IV. The exercises were expected to becarried out by programming them in occam and in ADA, with aview to introducing both languages and to providing scope forcomparison between the two languages and their provisionsfor concurrent programming.

D. Student Comment

As might be expected, the use of the emulator with studentshas been useful in improving its robustness, and several helpfulsuggestions have been provided on the presentation of theemulator. The emulator has found favor with students becausethe debugging aids it provides are rather more extensive thanthose on the actual transputer development system wherethey would otherwise work. This allows them to be steeredmore quickly into the way of thinking needed for parallelprogramming, reducing the time spent puzzling over obscureerrors. The slower speed of the emulation is noted by students,but rated a small problem for small programming exercises.

Students favored the familiar and powerful user interface,and expressed satisfaction with the menu structures and win-

dows provided. Overall, the student response was favorable,and the emulator was regarded as an effective way to learnthe language without having to become familiar with a newprogramming environment.

VII. EVALUATION

A. General

In use the occam emulator is capable of executing smallprograms of the sort that would be written by a student learningoccam programming. There are some limitations in its use,which are set out below.

In use the speed of execution of occam programs appearsrelatively slow on early machines such as the MacPlus. Thisis a consequence of compiling to intermediate code andinterpreting that code in Pascal. The emulator is not partic-ularly optimized for speed. However, performance on currentmachines with faster processors is quite acceptable, but couldof course always be improved.

B. Limitations

The emulator covers most aspects of the occam language,but has some limitations due either to the nonimplementationof certain features of the language or to the emulation process.

The emulator has no provision for accepting true externalinputs and delivering true external outputs. Thus it cannot beused as part of a larger system that provides or uses theseinputs and outputs. This limits the emulator to the teaching ofthe language or emulation of applications that do not requireinput/output.

The emulator clearly does not provide true multiprocessoroperation, and the time slicing arrangements will lead toimprecise time-dependent behavior in processes.

Some of the language is not yet implemented. Mostly theseare the instructions which interface an occam program runningon a transputer to its hardware. For instance, none of thelanguage relating to configuration of links between transputers,nor the allocation of processes to particular processors isimplemented (except the ANY protocol). It is, therefore, notpossible to place a particular process on a particular processoror place a particular channel on a particular Inmos link. Also, itis not possible to specify the exact bit pattern used to representvalues.

In the present form of the emulator procedures and functionsare not implemented. Procedures are useful in occam in thesame way as any other imperative language: they make theprogram code more transparent. The programming exercisesenvisaged do not always benefit greatly from the use ofprocedures and functions, and the loss of transparency inexercises that could usefully employ procedures and functionsis not intolerable.

The emulator could not be relied upon to execute an occamprogram copied directly from an implementation written to runon a real transputer network, because some of the hardware-dependant features cannot be provided. However, it is capableof running small programs developed by students on a sim-ple occam course that concentrates on the principles of thelanguage rather than implementation details.

Page 6: Emulation of the occam(TM) parallel programming language

6 IEEE TRANSACTIONS ON EDUCATION, VOL. 40, NO. 1, FEBRUARY 1997

VIII. C ONCLUSION

The emulator was able to successfully identify programfaults in a variety of programs and to execute a range ofprograms at an acceptable speed, with debugging operatingat a range of grain sizes. Even with the finest grain size thespeed of operation was adequate for small programs on oldermachines, and satisfactory on newer machines.

The occam emulator offers the advantages of the user-friendly GUI of the Apple Macintosh for application access,entry, and editing of programs, and for display of results. Theemulator is able to interact with the “outside world” via thekeyboard, mouse, and display, and is suited to educational ordevelopmental applications.

The emulator can evaluate all valid occam expressions(including bit manipulation such as bit shifting, bit AND/OR,etc.) and carry out input or output of information over key-board and terminal channels. The emulator will execute se-quential and parallel occam constructs.

The emulator is able to provide a useful tool for teachingbasic occam programming concepts.

APPENDIX IOCCAM PRIMITIVES AND CONSTRUCTIONS

occam is made up of primitive statements incorporatedinto Constructors. The full definition of the syntax of occamcan be found in standard references [17]. A brief outline ofthe language primitives and some of the more specialisedconstructs in the language now follow.

A. Primitives

AssignmentAssignment is indicated by the symbol “:=”.

amplification := 10Sets the variable “amplification” to andterminates.

InputAn input is indicated by the symbol “?”.

switch ? volumeInputs a value from channel “switch” and assigns itto the variable “volume.”

OutputAn output is indicated by the symbol “!”.

speakers ! volumeOutputs the value assigned to the variable “volume”to the channel “speakers.”

B. Constructs

Sequential ConstructA sequential construct is indicated by the “SEQ”keyword.SEQ

P1P2P3

The component processes—P1, P2, P3—are executed oneafter the other. Each process starts after the previous oneterminates. The construct terminates when the last componentprocess terminates.

Parallel ConstructA parallel construct is indicated by the “PAR” keyword.PARP1P2P3

The component processes (P1, P2, P3) are executed si-multaneously. The construct terminates only when ALL theprocesses P1, P2, P3 have terminated. Concurrent processescommunicate only by using channels, to ensure communica-tion is synchronized. Communication only takes place whenboth the sending and receiving processes are ready, the“ready”process is suspended until then.

Conditional ConstructA conditional construct enables one of a number of pro-

cesses to be executed depending on the result of the guardcondition.

IF x = 10 P1x = 11 P2

The conditions are evaluated in the order they are presented,the first condition evaluated to true enables the associatedcomponent process to be executed. Once the process termi-nates the conditional construct itself terminates. Only one ofthe processes defined in a conditional construct can ever beexecuted.

Alternative ConstructAn alternative process waits until one of the input guards

becomes ready, at this point the input takes place and theassociated component process is executed. Once the processterminates the ALT construct terminates. This construct pro-vides a method of handling external and internal events thatmust be handled by assembly level interrupts in a conventionalprogramming language If two guards are ready simultaneously,a random selection is made to determine which one proceeds.

ALTinput1 ? v P1input2 ? v P2input3 ? v P3

RepetitionRepeated execution of a process is carried out using aWHILE construct.WHILE (x 5) 0x := x 5

The component process is repeatedly executed until theresult of evaluating the expression becomes FALSE, at whichpoint the construct terminates

ReplicationA replicator is used with a constructor to replicate the

component process a number of times. When used with SEQconstruct it provides a conventional loop similar to a “FOR”loop in Pascal. Its most powerful feature is when used with aPAR construct as in the opposite example.

PAR i = [0 FOR n]Here an array of similar processes has been created

where the index takes the values in, respectively.

Page 7: Emulation of the occam(TM) parallel programming language

DOHERTY AND HARRIS: EMULATION OF THE occamTM PARALLEL PROGRAMMING LANGUAGE 7

APPENDIX IIEXAMPLE TRANSLATION TO INTERMEDIATE CODE

INT x, z [5]: Working Store “WS” Storage allocation.X [ ] 1Z [ ] 2

[ ] 3[ ] 4[ ] 5[ ] 6

VAL offset IS 2(INT):VAL control IS 15(INT):VAL enter IS 13(BYTE): evaluates to the value 13 (ASCII enter char)

SEQ CS adr Opcode OperandDescription

keyboard ? x 1 LDC-2 Load keyboard chan address3 LDC 1 Load address of “x”5 LDC 1 Load message length7 INM Input message

terminal ! x 8 LDC-1 Load terminal chan address10 LDL 1 Load contents of “x”12 LDC 1 Load length of message14 OUTM Output message on chan

z[offset+1] := x + 1 15 LDC 2 Load base address of “z”17 LDC 2 Load value of “offset’19 LDC 1 Load literal constant “1’21 ADD Add and put result on stack22 ADD Add puts correct offset into the “z” vector on stack23 LDL 1 Load contents of “x”25 LDC 1 Load literal constant “1”27 ADD Load expr result on stack28 STLP Store stack top at location addressed by stack top

terminal ! z[1+2]; enter29 LDC -1 Load terminal chan address31 LDC 2 Load address of “z”33 LDC 1 Load literal constant “1”35 LDC 2 Load literal constant “2”37 ADD Add and place result on stack38 ADD Add puts correct offset to the “z” vector on stack.39 LDLP Load stack with contents of location addressed by stacktop value40 LDC 1 Load message length.42 OUTM Output message.43 LDC 0 Load channel address. Zero signifies that the same chan as last output must be used.45 LDC 13 Load the return char.47 LDC 1 Load message length.49 OUTM Output message.50 HALT Quit execution.

Page 8: Emulation of the occam(TM) parallel programming language

8 IEEE TRANSACTIONS ON EDUCATION, VOL. 40, NO. 1, FEBRUARY 1997

APPENDIX IIISAMPLE PROGRAMS

(NOTES ON SAMPLE PROGRAMS)

Terminal I/O: The Occam specification makes no provisionfor terminal input and output. This is because transputers aredesigned to communicate with the outside links via Inmoslinks, accessed using channels. Usually, transputers commu-nicate with another processor, which provides display capa-bilities if they are needed for the application. The aims ofthe Occam interpreter are different from the usual transputerapplications and the interpreter must provide a way for Occamprograms to read data from the Macintosh keyboard and writeto a window in the screen. A window is provided by theemulator for program input and output.

Output to the screen is through a predefined channel called“terminal.” Output causes the value on the stack to be writtento the screen. If the values are bytes then the ASCII char-acter represented by that type is written, otherwise a stringrepresentation of the number is written.

Input from the keyboard is through a channel called “key-board,” and causes a number of characters to be read fromthe keyboard (depending on the message size) and a list ofbyte values representing the ASCII representation of thosecharacters to be returned. If numbers are entered they arereturned as the ASCII codes of the digits. You must convertfrom ASCII codes to integers if any arithmetic is to be doneby the program.

The use of the predefined channels is illustrated in thesampleprogram suite “IO test.”

• IO test 1:

illustrates writing to the screen, writing strings, characters,and integers that are coded into the program.

• IO test 2:

illustrates interaction with keyboard and screen, with writingof strings, characters, and numbers. The keyboard channelreturns ASCII codes one digit at a time. Multidigit inputrequires writing of handling code.

• IO test 3:

shows the run-time error that occurs if an attempt is made toread a number as an integer over the keyboard channel (whichhas been predefined as of type BYTE).

A major distinguishing feature of occam is the clear distinc-tion between parallel and sequential processing

• SEQ 1:

shows how one operation waits for its predecessor tocomplete in a SEQ construct.

• PAR 1:

shows how the execution swaps between the parallel pro-cesses.

The count continues to grow until a key is pressed, whenthe value of the number is added to the count, which thenresumes.

Note how the count is slower while the key input is beingchecked, but faster after that, indicating that the first processis completed after the key has been pressed. The parallelconstruct is exited when both processes are completed, the

first after the key has been pressed and the second at the endof the count. Follow through the execution of the program toproduce the results that appear on the screen.

• PAR 2:

extends the previous example: the keyboard input is now ina loop. Note that even though the counter may have finishedthe loop the keyboard loop is waiting at the key input toproceed, and a key may have to be entered to allow bothprocesses to complete.

The notion of interprocess communication over single chan-nels using a mutual readiness protocol can be illustrated withthe “channels” sample program.

• CHANNELS:

puts data values on to channels and, in parallel, reads thevalues into a variable. These can be in parallel because theread cannot proceed till data is made available on the channel.

The selection from among multiple inputs is important toa language that is intended for real-time application. The fullfeatures cannot be illustrated by this simulation, but the sampleprogram gives a flavor of the ALT construct and the use ofguards.

• ALT:

The selector function of the ALT construct is illustratedby having three counters that are accessed through guardsto count the number of times a particular number is entered.The emulation cannot create the situation where two guardsare enabled at the same time, causing the ALT construct torandomly choose between them.

Timing is important in a real-time language. The facilitiesfor implementing delays and measuring time provided inoccam are illustrated here.

• TIMER:

The timer is used to generate delays, and can be read togive a measure of time.

THE SAMPLE PROGRAMS

IO test 1

—Illustrates terminal output—The channel “terminal” has been predefined—as a channel of type ANY—This program writes a string, byte (char), and integer

VAL CR IS 13(BYTE):BYTE x:INT y:SEQ

terminal ! “writing string”; CR; “char, integer toscreen”; CRx := ‘A’terminal ! x;CRy := 50terminal ! y;CR

IO test 2

—Reading from keyboard—The channel “keyboard” has been predefined—as a channel of BYTE

Page 9: Emulation of the occam(TM) parallel programming language

DOHERTY AND HARRIS: EMULATION OF THE occamTM PARALLEL PROGRAMMING LANGUAGE 9

—so it returns ASCII value for keys pressed—this needs care with numeric input

—NOTE: need to convert entered number to INT—but can output as integer because “terminal” is of type

ANY

VAL CR IS 13(BYTE):VAL msg1 IS “press any letter key”:VAL msg2 IS “press any number key”:VAL msg3 IS “to enter three digit number needloop”:BYTE x:INT y:SEQ

terminal ! CR; msg1; CR

keyboard ? x

terminal ! x;CR

terminal ! msg2;CR

keyboard ? x—number is BYTE

y := INT x—convert to integer

terminal ! “The ASCII code of the number is”; y;CR

terminal ! “subtract 48 to extract digit”;CR

y := y 48

terminal ! “the number was”; y;CR

IO test 3

VAL CR IS 13(BYTE):VAL MSG IS “press any numeric key”:INT x:SEQ

terminal ! MSG;CR

keyboard ? x

terminal ! x; “key has been read”;CR

SEQ 1

—SEQ demo—for contrast with PAR demo

—waits for integer to be input at kbd—then adds to running total of inputs—exits when total > 25

VAL CR IS 13(BYTE):BYTE x:INT y:

SEQy := 0WHILE y ¡ 25

SEQterminal ! “press any number key”;CRkeyboard ? xy := (INT x) + yy := y 48terminal ! y;CR

terminal ! “finished’;CR

PAR 1

—PAR demo—for contrast with SEQ demo

—allows simultaneous input of integer at kbd—with number input added to running total—while waiting adds one to running total—thus waiting and handling of kbd is parallel to incre-

menting—exits when total > 25

VAL CR IS 13(BYTE):BYTE x:INT y:INT z:

SEQy:=0WHILE y 25SEQ—after completion of PAR write to screenPAR—two processes in parallel

—process # 1SEQ

terminal ! “press any number key;”terminal ! CRkeyboard ? xz := INT xy := y + (z 48)terminal ! “kbd”terminal ! yterminal ! CR

—process #2SEQ

y := y + 1terminal ! “increment;”terminal ! yterminal ! CR

—END of PAR constructterminal ! “finished PAR, total is”;y;CR

terminal ! “finished’;CR

PAR 2

—PAR demo—for contrast with SEQ demo

—allows simultaneous input of integer at kbd—with number input added to running total—while waiting adds one to running total—thus waiting and handling of kbd is parallel to incrementing—exits when total > 25

VAL CR IS 13(BYTE):BYTE x:INT y:INT z:

Page 10: Emulation of the occam(TM) parallel programming language

10 IEEE TRANSACTIONS ON EDUCATION, VOL. 40, NO. 1, FEBRUARY 1997

SEQy:=0WHILE y 25

SEQ—after completion of PAR write to screenPAR—two processes in parallel

—process # 1WHILE y 25SEQ

terminal ! “press any number key;”terminal ! CRkeyboard ? xz := INT xy := y + (z 48)terminal ! “kbd”terminal ! (z 48)terminal ! CR

—process # 2WHILE y 25SEQ

y := y+1terminal ! “count;”terminal ! yterminal ! CR

—END of PAR constructterminal ! “finished PAR, total is”;y;CR;CR

terminal ! “finished”;CR

CHANNELS—Channel communication

VAL CR IS 13(BYTE):

CHAN OF INT32 long.chan:CHAN OF REAL32 real.chan:CHAN OF [3]BYTE string.chan:PROTOCOL complex IS REAL32; REAL32:CHAN OF complex complex.chan:

INT32 long:REAL32 real, r, i:[3]BYTE string:

SEQ—Send and receive examplesPAR

—Send data over channellong.chan ! 40 000(INT32)real.chan ! 12.3(REAL32)string.chan ! “ABC”complex.chan ! 45.5(REAL32);23.2(REAL32)—Read the channels and store the value sent ina variablelong.chan? longreal.chan? real

string.chan? stringcomplex.chan? r; i

—Print variable valuesterminal ! CRterminal ! “longint”; long; CRterminal ! “real”; real; CRterminal ! “string”; string; CRterminal ! r; “+”; “i”; i

ALTVAL CR IS 13(BYTE):INT count, c1, c2, c3, y:BYTE x:SEQ

count := 0terminal ! CR;“enter 1,2 or 3.”;CRterminal ! “The number of times each is entered willbe counted”;CRterminal ! “five entries will be accepted”;CR

WHILE count 5SEQ

keyboard ? xy := (INT x) 48

ALTy = 1 & SKIP—need & SKIPto complete guardconstruct

SEQc1 := c1 +1terminal ! “c1”; c1; CR

y = 2 & SKIPSEQ

c2 := c2 +1terminal ! “c2”; c2; CR

y 2 & SKIPSEQ

c3 := c3 + 1terminal ! “c3”; c3 ;CR

count := count +1

terminal ! “SUMMARY”;CRterminal ! “c1”;c1;CRterminal ! “c2”;c2;CRterminal ! “c3”;c3;CR

TIMER—Timers—Demonstrates use of a delayed input—to cause a wait, and timer input to—read the clock.

VAL CR IS 13(BYTE):TIMER t:

Page 11: Emulation of the occam(TM) parallel programming language

DOHERTY AND HARRIS: EMULATION OF THE occamTM PARALLEL PROGRAMMING LANGUAGE 11

INT x:BYTE b:SEQ

terminal ! “the timer will be read after a delayof 5000 clock cycles”;CRterminal ! “start timer”;CRt ? AFTER 5000t ? xterminal ! “timer reading is”; x; CRterminal ! “now press a key and it will be echoed aftera delay”; CRkeyboard? bt? xterminal ! x; CRt ? AFTER (x + 2000)terminal ! “key was”; b; CRt ? xterminal ! “timer reading”; x; CR

APPENDIX IVSAMPLE QUESTIONS

The following question outlines are designed to providea simple problem that can be addressed with parallel solu-tions. They are fairly standard problems in texts on parallelprogramming or occam programming. The student would beexpected to code in both ADA and occam, and to compare theapplicability of the two languages in each situation.

Hamming Code:Write a program to accept four bits andto generate the Hamming bits. (The Hamming bit generationcan start in parallel with thekeyboard input).

Matrix Multiplication: Write a program to multiply twomatrices. (Again processing can be in parallel with

keyboard input).Tree Search:Write a program that will search a four-level

tree in parallel.Pipeline: Write a program to implement a pipeline solution

of the Newton–Raphson approximation.Multiplexer: Write a program to accept sequentially inputs

from different channels, and deliver them as a sequentialstream on a single channel.

ACKNOWLEDGMENT

Acknowledgment is made for the use or computing facilitiesat Aston University, and for use of, and advice on theMacintosh application shell ‘QuickApp’ [22] developed byP. Coxhead of Aston University. The original emulator wasextended by A. J. Wiles to emulate the extra features of theoccam 2 language.

REFERENCES

[1] Inmos Ltd., occam Programming Manual., Hoare, Ed. EnglewoodCliffs, NJ: Prentice-Hall, 1984.

[2] I. M. Barron, “The transputer,” inMicroprocessor and Its Applications.Cambridge, U.K.: Cambridge Univ. Press, 1978.

[3] C. A. R. Hoare, “Communicating sequential processes,”Comm ACM,vol. 21, pp. 666–677, Aug. 1978.

[4] , Communicating Sequential Processes. Englewood Cliffs, NJ:Prentice-Hall, 1985.

[5] A. Burns,Programming in occam 2(The Instruction Set Series). Wok-ingham, U.K.: Addison-Wesley, 1988.

[6] M. R. Smith, “A microprogrammable microprocessor simulator anddevelopment system,”IEEE Trans. Educ., vol. E-27, pp. 93–100, May1984.

[7] R. Yen and Y. Kim, “Development and implementation of an edu-cational simulator software package for a specific microprogrammingarchitecture,”IEEE Trans. Educ., vol. E-29, pp. 1–11, Feb. 1986.

[8] M. Cutler and R. R. Eckert, “A microprogrammed computer simulator,”IEEE Trans. Educ., vol. E-30, pp. 135–141, Aug. 1987.

[9] J. J. Devore and D. S. Hardin, “A computer design for introducinghardware and software concepts,”IEEE Trans. Educ., vol. E-30, pp.219–226, Nov. 1987.

[10] H. B. Diab and I. Demashkieh, “A computer-aided teaching packagefor microprocessor system education,”IEEE Trans. Educ., vol. 34, pp.179–183, May 1991.

[11] M. Cutler and R. R. Eckert, “Microprogrammed computer simulatortools,” IEEE Trans. Educ., vol. 33, pp. 212–220, May 1990.

[12] W. K. Fuchs, W. Page, J. H. Patel, and P. Tobin, “Workstation-based logic animation and microarchitecture emulation for teachingintroduction to computer engineering,”IEEE Trans. Educ., vol. 32, pp.218–225, Aug. 1989.

[13] R. J. Distler, “A simulator for a bit-slice computer,”IEEE Trans. Educ.,vol. 33, pp. 363–365, Nov. 1990.

[14] L. Rizzo, “Simulation and performance evaluation of parallel softwareon multiprocessor systems,”Microproc. and Microsys., vol. 13, pp.39–46, Jan./Feb. 1989.

[15] A. Houri and E. Shapiro, “Sequential abstract machine for flat concurrentprolog,” J. Logic Progr., vol. 7, pp. 85–123, Sept. 1989.

[16] C. Mills, S. C. Ahalt, and J. Fowler, “Compiled instruction set simu-lation,” Software-Practice and Experience, vol. 21, pp. 877–889, Aug.1991.

[17] D. Macfarlane, M. Webb.-Johnson, and J. Gallety, “PC—occam,”J.Microcomp. Appl., vol. 12, pp. 191–212, Mar. 1989.

[18] B. S. Doherty and S. A. J. Harris, “Execution emulation of theoccam parallel programming language,” in1st World Conf. on ParallelComputing in Engineering and Engineering Education(Paris, France,1990), pp. 145–149.

[19] A. V. Aho, R. Sethi, and J. D. Ullman,Compilers: Principles, Tech-niques, and Tools. Reading, MA: Addison-Wesley, 1985.

[20] R. Bornat,Writing and Understanding Compilers(Macmillan ComputerScience Series), London, U.K.: Macmillan, 1979.

[21] A. J. Davie and R. Morrison,Recursive Descent Compiling(The EllisHorwood series in Computers and their Applications). Chichester,U.K.: Ellis Horwood, 1981.

[22] P. Coxhead,Introduction to QuickApp: A Tool for Macintosh Program-ming, TR88004, Aston Univ., Dec.1988.

Bernard S. Doherty was born in Latrobe, Australia, on October 2, 1945.He graduated from the University of Melbourne, Australia, in electricalengineering in 1967, and arts in 1971, and received the Master of EngineeringScience degree in 1980, also from the University of Melbourne.

Prior to 1980, he was employed in power generation and telecommuni-cations manufacturing industries. He was appointed Lecturer in ElectricalEngineering at the University of Aston in Birmingham, England in 1980,then Lecturer in Computer Science, in 1985. His current interests are in real-time systems, computer networks, and application of artificial intelligence tothe requirements elicitation phase of system analysis and specification.

Mr. Doherty is a member of the Institution of Electrical Engineers and theBritish Computer Society.

Steven A. J. Harris was born in London, England, on March 20, 1966. Hegraduated from Aston University, Birmingham, England, with a First ClassHonours degree in computer science in 1988.

He is currently the Western Europe Regional Manager at Wind RiverSystems UK Limited, who are developers of real-time operating systemsoftware and embedded development tools.