communicating sequential processes …ptolemy.eecs.berkeley.edu/publications/papers/98/cspin...the...

39
Masters Report COMMUNICATING SEQUENTIAL PROCESSES DOMAIN IN PTOLEMY II by Neil Smyth Memorandum No. UCB/ERL M98/70 15 December 1998 ELECTRONICS RESEARCH LABORATORY College of Engineering University of California, Berkeley 94720

Upload: others

Post on 13-Aug-2020

6 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

COMMUNICATING SEQUENTIAL PROCESSESDOMAIN IN PTOLEMY II

by

Neil Smyth

Memorandum No. UCB/ERL M98/70

15 December 1998

ELECTRONICS RESEARCH LABORATORY

College of EngineeringUniversity of California, Berkeley

94720

Masters Report

Page 2: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

Ptolemy II

Page 3: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

em as. Thero- non-s anandular,odel-

mbed-of

ABSTRACT

The Communicating Sequential Processes (CSP) domain in Ptolemy II models a systa network of processes communicating with messages through unidirectional channelscommunication between processes is rendezvous based: both the reading and writing pcesses block until the other side is ready to communicate. This model of computation isdeterministic and is also highly concurrent due to the nature of the model. This report giveoverview of the semantics of the model of computation of the CSP domain, the algorithmssoftware infrastructure used in implementing the domain, and some applications. In particapplications for the CSP domain include resource management and high level system ming early in the design cycle. Resource management is often required when modeling eded systems, and to further support this, a notion of time has been added to the model computation used in the domain.

Masters Report

Page 4: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

nce

prob-

dis-

eola,

ACKNOWLEDGEMENTS

I would first like to thank my advisor, Professor Edward Lee, for his support and guidaduring my time in the Ptolemy group. I really enjoyed my interactions with him, and willalways be grateful for showing me that there are many different ways to view the same lem.

Secondly, I would like to say thanks to all the members of the Ptolemy group, for thecussions and interactions that made my time in Berkeley such an enjoyable one.

This research is sponsored by the Defense Advanced Research Programs Agency(DARPA), the State of California MICRO program, and the following companies: cadencdesign Systems, Hewlett Packard, Hitachi, Hughes Space and Communications, MotorNEC, and Philips.

Finally, this report is dedicated to my parents and family, without whom none of thiswould have been possible.

Ptolemy II

Page 5: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

1. Introduction 12. Semantics of the Ptolemy II CSP Model 2

2.1.Rendezvous 22.2.Conditional communication constructs 3

2.2.1. CIF: 32.2.2. CDO: 42.2.3. Example using a CDO 4

2.3.Deadlock 42.4.Time 42.5.Differences from original CSP model as proposed by Hoare 5

3. Software infrastructure 63.1.Modeling in Ptolemy II 63.2.CSP Domain 73.3.Messages 9

4. Using the CSP domain in Ptolemy II 104.1.Rendezvous 104.2.Conditional communication constructs 104.3.Time 13

5. Model setup and control 145.1.Starting the model 145.2.Detecting deadlocks: 155.3.Terminating the model: 165.4.Pausing/resuming the model 17

6. Controlling communication between Threads 186.1.Brief introduction to threads in Java 18

6.1.1. Approaches to locking used in the CSP domain 186.2.Rendezvous algorithm 196.3.Conditional Communication Algorithm 21

6.3.1. Built on top of rendezvous: 216.3.2. Choosing which branch succeeds 226.3.3. Algorithm used by each branch: 22

6.4.Modification of rendezvous algorithm: 247. Demos and Examples 26

7.1.Dining Philosophers. 267.2.M/M/1 277.3.Pausing M/M/1 277.4.Sieve of Eratosthenes 27

8. Changes to the Topology during the Execution of a Model 288.1.How to write an actor that uses Topology Changes 288.2.Sieve of Eratosthenes example 28

9. Composing CSP with other domains 309.1.CSP inside another domain 30

9.1.1. CSP within CSP 319.2.Another domain inside CSP 31

Masters Report

Page 6: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

10. Design decisions 3310.1.Time: distributed relative time versus centralized absolute time 3310.2.Choice of locks used and locking points 3310.3.Making all the communication mechanisms symmetric 3310.4.Conditional communication mechanisms upon rendezvous 3310.5.Points in the model when changes to the topology are allowed 34

11. Conclusion and Future Work 35

Ptolemy II

Page 7: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

nt sys-nified

maysed, to

a net-s readyess isunica-

until thess canue to

odel-ed sys-sed in

do not[6]. Itimeds the

g how. For

1. Introduction

Ptolemy II is an environment that supports heterogeneous modeling and design of concurretems. Its focus is on embedded systems, particularly those that mix technologies. It offers a uinfrastructure for modeling systems using a number of models of computation. Adomainexecutes amodel of a system with the semantics of a particular model of computation. A model of a systembe designed using one domain, or it may choose to use several domains, hierarchically compoachieve greater accuracy or efficiency.

The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system aswork of processes communicating with messages through unidirectional channels. If a process ito send a message, it blocks until the receiving process is ready to accept it. Similarly if a procready to accept a message, it blocks until the sending process is ready to send it. Thus the commtion between processes is rendezvous based as both the reading and writing processes blockother side is ready to communicate. This model of computation is non-deterministic as a procebe blocked waiting to send or receive on any number of channels. It is also highly concurrent dthe nature of the model.

The applications for the CSP domain include resource management and high level system ming early in the design cycle. Resource management is often required when modeling embeddtems, and to further support this, a notion of time has been added to the model of computation uthe domain. This differentiates our CSP model from those more commonly encountered, whichtypically have any notion of time, although several versions of timed CSP have been proposedmight thus be more accurate to refer to the domain using our model of computation as the “TCSP” domain, but since the domain can be used with and without time, it is simply referred to aCSP domain.

This report is written to be as self contained as possible, but invariably some details regardinit builds upon the infrastructure in the Ptolemy II kernel and actor packages had to be omittedmore details on these aspects, and on Ptolemy II in general, please refer to [13].

Masters Report 1 of 33

Page 8: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

sed byng viare is nothe send-rocess’ book

hronous

t alsoannels.g end,e FIFO

also dif-ication

cept it.to sendwriting

ne pro-tion in

processcide to

.

2. Semantics of the Ptolemy II CSP Model

The model of computation used in the CSP domain is based on the CSP model first propoHoare[7] in 1978. In this model, a system is modeled as a network of processes communicatimessages along unidirectional channels. This in the only way processes can communicate, theshared state. The transfer of message between processes is via rendezvous, which means bothing and receiving of a messages from a channel are blocking: i.e. the sending or receiving pstalls until the message is transferred. Some of the notation used here is borrowed from Andrewson concurrent programming [1], which refers to rendezvous-based message passing as syncmessage passing.

Process Networks (PN)[9] is a model of computation that has much in common with CSP. Iconsists of a network of processes communicating via message passing along unidirectional chHowever, in PN, each channel has an unbounded first-in-first-out (FIFO) queue at the receivinso that the sending of messages along a channel is non-blocking. If there are no messages in thqueue, then the receiving process stalls until a message is sent to the channel. The two modelsfer in that PN is determinate whereas CSP is non-determinate due to the conditional communconstructs described below in section 2.2.

2.1 RENDEZVOUS

If a process is ready to send a message, it blocks until the receiving process is ready to acSimilarly if a process is ready to accept a message, it blocks until the sending process is readyit. Thus the communication between processes is rendezvous based as both the reading andprocesses block until the other side is ready to communicate. Figure 1 shows the case where ocess is ready to send before the other process is ready to receive. The communication of informathis way can be viewed as a distributed assignment statement.

The sending process places some data in the message that it wants to send. The receivingassigns the data in the message to a local variable. Of course, the receiving process may deignore the contents of the message and only concern itself with the fact that a message arrived

Process A Process B

send(B, msg)

receive(A, var)

progress

blocked

transfer of data

FIGURE 1. Illustrating how processes block waiting to rendezvous

2 of 33 Ptolemy II

Page 9: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

rmin-

state

not becon-

ecuted.ments

state--rdedin

hichnch isan onee non-

xecutedg state-

ncur-e nota-

nstructprogress

2.2 CONDITIONAL COMMUNICATION CONSTRUCTS

A lot of the expressiveness in the CSP model comes from the being able to perform nondeteistic rendezvous. Nondeterministic rendezvous is based uponguarded communication statements.

A guarded communication statement has the form

guard; communication => statements;

Theguard is only allowed to reference local variables, and its evaluation cannot changes theof the process. For example it is not allowed to assign to variables, only reference them. Thecommuni-cationmust be a simple send or receive, i.e. another conditional communication statement canplaced here. Thestatementspart can contain any arbitrary sequence of statements, including moreditional communications.

If the guard is false, then the communication is not attempted and the statements are not exIf the guard is true, then the communication is attempted, and if it succeeds, the following stateare executed. The guard may be omitted, in which case it is assumed to be true.

There are two conditional communication constructs built upon the guarded communicationments:CIF andCDO. These are analogous to theif andwhile statements in most programming languages. They should be read as “conditional if” and “conditional do”. Note that each guacommunication statement represents onebranchof the CIF or CDO. The communication statementeach branch can be either a send or a receive, and they can be mixed freely.

2.2.1 CIF:

The form of a CIF is

For each branch in the CIF, the guard (G1, G2,...) is evaluated. If it is true (or absent, wimplies true), then the associated communication statement is enabled. If one or more braenabled, then the entire construct blocks until one of the communications succeeds. If more thbranch is enabled, the choice of which enabled branch succeeds with its communication is maddeterministically. The successful communication is carried out, the associated statements are eand the process continues. If all of the guards are false, then the process continues executinments after the end of the CIF.

It is important to note that, although this construct is analogous to the commonif programmingconstruct, its behavior is very different. In particular all guards of the branches are evaluated corently, and the choice of which one succeeds does not depend on its position in the construct. Thtion “[]” is used to hint at the parallelism in the evaluation of the guards. In a commonif the branchesare evaluated sequentially and the first branch that is evaluated to true is executed. The CIF coalso depends on the semantics of the communication between processes, and can thus stall the

CIF {G1;C1 => S1;

[]G2;C2 => S2;

[]...

}

Masters Report 3 of 33

Page 10: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

d theCDOs

but hasat in

orever.

eitheradlock

, and

ime,

of the thread if none of the enabled branches is able to rendezvous.

2.2.2 CDO:

The form of the CDO is

The behavior of the CDO is similar to the CIF in that for each branch the guard is evaluated anchoice of which enabled communication to make is taken nondeterministically. However therepeats the process of evaluating and executing the branches untilall the guards return false. When thihappens the process continues executing statements after the CDO construct.

2.2.3 Example using a CDO

An example use of a CDO is in a buffer process which can both accept and send messages,to be ready to do both at any stage. The code for this would look similar to that in figure 2. Note ththis case both guards can never be simultaneously false so this process will execute the CDO f

2.3 DEADLOCK

A deadlock situation is one in which none of the processes can make progress: they are allblocked trying to rendezvous or they are delayed (see the next section). Thus two types of decan be distinguished:

real deadlock - all active processes are blocked trying to communicatetime deadlock - all active processes are either blocked trying to communicate or are delayedat least one processes is delayed.

2.4 TIME

In the CSP domain,time is centralized. That is, all processes in a model share the same t

CDO {G1;C1 => S1;

[]G2;C2 => S2;

[]...

}

CDO {(room in buffer?); receive(input, beginningOfBuffer) => update pointer to beginning of buffer;

[] (messages in buffer?); send(output, endOfBuffer) => update pointer to end of buffer;

}

FIGURE 2. Example of how a CDO might be used in a buffer

4 of 33 Ptolemy II

Page 11: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

rrentose towait-

ndeddelaysf the

ached.an haveed, anyusing

ous,occurs,

dvancedprocesstime

cution,d time,using

la[5],

twooughossiblellowedlow both

pro-t wasS[3]

mes-uctionSim-that

referred to as thecurrent model time. Each process can only choose todelay itself relative for someperiod from the current model time, or a process can wait for time deadlock to occur at the cumodel time. Even though a process can be aware of the current model time, it should not chowait until the current model time reaches some value as the model time could change while it ising. It both cases, a process is said to bedelayed.

When a process delays itself for some length of time from the current model time, it is suspeuntil time has sufficiently advanced, at which stage it wakes up and continues. If the processitself for zero time, this will have no effect and the process will continue executing. An example ouse of time in this manner can be seen below in section 7.2.

A process can also choose to delay its execution until the next occasion a time deadlock is reThe process resumes at the same model time at which it delayed, and this is useful as a model cseveral sequences of actions at the same model time. The next occasion time deadlock is reachprocesses delayed in this manner will continue, and time will not be advanced. An example oftime in this manner can be found in section 8.2.

Time may beadvancedwhen all the processes are delayed or are blocked trying to rendezvand at least one process is delayed. If one or more processes are delaying until a time deadlockthese processes are woken up and time is not advanced. Otherwise, the current model time is ajust enough to wake up at least one process. Note that there is a semantic difference between adelaying for zero time, which will have no effect, and a process delaying until the next occasion adeadlock is reached.

Note also that time, as perceived by a single process, cannot change during its normal exeonly at rendezvous points or when the process delays. A process can be aware of the centralizebut it cannot influence the current model time except by delaying itself. One of reasons behindthis model for time is given in 10.1. The choice for modeling time was in part influenced by Pamea run time library that is used to model parallel programs.

2.5 DIFFERENCES FROM ORIGINAL CSP MODEL AS PROPOSED BY HOARE

The model of computation used by the CSP domain differs from the original CSP[7] model inways. First, a notion of time has been added. The original proposal had no notion of time, alththere have been several proposals for timed CSP[6]. Second, as mentioned in section 2.2, it is pto use both send and receive in guarded communication statements. The original model only areceives to appear in these statements, though Hoare subsequently extended their scope to alcommunication primitives[8].

One final thing to note is that in much of the CSP literature, send is denoted using a “!”,nounced “bang”, and receive is denoted using a “?”, pronounced “query”. This syntax was whaused in the original CSP paper[6] by Hoare. For example, the languages OCCAM[2] and LOTOboth follow this syntax. In the CSP domain in Ptolemy II we usesendandget, the choice of which isinfluenced by the desire to maintain uniformity of syntax across domains in Ptolemy II that usesage passing. This supports the heterogeneity principle in Ptolemy II which enables the constrand interoperability of executable models that are built under a variety of models of computation.ilarly, the notation used in the CSP domain for conditional communication constructs differs fromcommonly found in the CSP literature.

Masters Report 5 of 33

Page 12: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

heompu-

d rela-on-

set of

yths ofinput

A dia-own in

cturemod-[13].

dchannelnds oriagram

ses that

3. Software infrastructure

3.1 MODELING IN PTOLEMY II

In Ptolemy II an executable model consists of a top-levelCompositeActorwith an instance ofDirector and an instance ofManagerassociated with it. The manager provides overall control of texecution (starting, stopping, pausing). The director implements the semantics of the model of ctation that governs the execution ofactors contained by the CompositeActor.

The actors in the CompositeActor are connected toRelationsvia Ports. A relation connects one ormore ports together. A particular collection of actors connected to each other through ports antions is called atopology. The choice of the actors, the director controlling them and how they are cnected defines what the model will do.

An actor under control of a director may be either anAtomicActor, which means it is indivisible, orit may be a CompositeActor, in which case it too can have its own director and contain a newactors. This is illustrated in figure 4(a).

Messages are passed between actors along relations. A relation has awidth, greater than or equal toone. The width of a relation is the number of datachannelsrepresented by it. A port may have annumber of relations connected to it, and the width of the port is defined to be the sum of the widthe relations connected to it. If the port is an input port, it contains a set of receivers, one for eachchannel. The receivers contained by a port are determined by the director controlling the model.gram illustrating how a message is transferred across a relation with one and two channels is shfigure 4(b).

Obviously what has just been described is a very rough overview of the software infrastruprovided by Ptolemy II, though hopefully it is enough to allow the reader to understand the CSPels which are built on top of it. For a much more thorough description of Ptolemy II in general see

3.2 CSP DOMAIN

In a CSP model, the director is an instance ofCSPDirector. Since the model is controlled by aCSPDirector, all the receivers in the ports areCSPReceivers. The combination of the CSPDirector anCSPReceivers in the ports gives a model CSP semantics. The CSP domain associates eachwith exactly one receiver, located at the receiving end of the channel. Thus any process that sereceives to any channel will rendezvous at a CSPReceiver. Figure 5 shows the static structure dof the five main classes in the CSP kernel, and a few of their associations. These are the clasprovide all the infrastructure needed for a CSP model.

Ptolemy II Syntax OCCAM syntax

send !

get ?

CIF ALT

CDO ALT wrapped in a while loop.

FIGURE 3. Comparison of syntaxes used in CSP domain and in OCCAM

6 of 33 Ptolemy II

Page 13: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

ntrols/neces-

nec-

by

CSPDirector: gives a model CSP semantics. It takes care of starting all the processes and coresponds to both real and time deadlocks. It also maintains and advances the model time whensary.

CSPReceiver:ensures that communication of messages between processes is via rendezvous.

CSPActor: adds the notion of time and the ability to perform conditional communication.

ConditionalReceive, ConditionalSend:used to construct the guarded communication statementsessary for the conditional communication constructs.

3.3 MESSAGES

All messages in Ptolemy II are represented byTokens. The data carried in a message is defined

P2P1

E1

E2

send(0,t)receiver.put(t) get(0)

token tR1

P2P1E1 E2

send(0,t0) get(0), get(1)

token t0, t1R1send(1,t1)

2

receiver.put(t0)receiver.put(t1)

2 2

P6 P3P2 P5P1

E1

E2

E4

E0

M: Manager

D1: local director

D2: local director

P4 P7

E3

E5

(a)

(b)

FIGURE 4. (a) Example of a topology illustrating the control of a model and how the model may behierarchically composed, (b) Detailed view of a relation with one and two channels in Ptolemy II.

Masters Report 7 of 33

Page 14: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

eveloptokens

the type of token used. The tokens available are shown in figure 6, though the user is free to dnew token classes. For more information on the token classes refer to [13]. For most models thesupplied should be sufficient.

ConditionalBranch

+ConditionalBranch(guard : boolean, port : IOPort, branchID : int)+getID() : int+getGuard() : boolean+getParent() : CSPActor+getReceiver() : CSPReceiver+getToken() : Token+isAlive() : boolean+setAlive(value : boolean)#_checkAndWait()

-_alive : boolean-_branchNumber : int-_guard : boolean-_parent : CSPActor#_receiver : CSPReceiver#_token : Token

ConditionalReceive

+ConditionalReceive(guard : boolean, port : IOPort, channel : int, id : int)+run()

ConditionalSend

+ConditionalSend(guard : boolean, port : IOPort, channel : int, id : int, t : Token)+run()

CSPActor

+CSPActor()+CSPActor(ws : Workspace)+CSPActor(cont : CompositeActor, name : String)+chooseBranch(branches : ConditionalBranch[]) : int+delay()+delay(delta : double)+terminate()#_branchBlocked()#_branchFailed(branchNumber : int)#_branchSucceeded(branchNumber : int)#_branchUnblocked()#_continue()#_isBranchFirst(branchNumber : int) : boolean#_releaseFirst(branchNumber : int)

-_blocked : boolean-_branchesActive : int-_branchesBlocked : int-_branchesDelayed : int-_branchTrying : int-_delayed : boolean-_internalLock : Object-_successfulBranch : int-_threadList : LinkedList

CSPReceiver

+CSPReceiver()+CSPReceiver(p : IOPort)+get() : Token+put(token : Token)+getContainer() : Nameable+hasRoom() : boolean+hasToken() : boolean+setContainer(parent : IOPort)+setFinish()+setPause(newValue : boolean)#_getOtherParent() : CSPActor#_isConditionalReceiveWaiting() : boolean#_isConditionalSendWaiting() : boolean#_isGetWaiting() : boolean#_isPutWaiting() : boolean#_setConditionalRecieve(v : boolean, parent : CSPActor)#_setConditionalSend(v : boolean, parent : CSPActor)#_checkAndWait()

-_conditionalReceiveWaiting : boolean-_conditionalSendWaiting : boolean-_container : IOPort-_getWaiting : boolean-_putWaiting : boolean-_otherParent : CSPActor-_rendezvousComplete : boolean-_simulationPaused : boolean-_simulationFinished : boolean-_token : Token

CSPDirector

+CSPDirector()+CSPDirector(name : String)+CSPDirector(name : String, ws : Workspace)+getCurrentTime() : double+setCurrentTime(newTime : double)+setUntimed(value : boolean)#_actorBlocked()#_actorDelayed(delta : double, actor : CSPActor)#_actorUnblocked()

-_actorsBlocked : int-_actorsDelayed : int-_currentTime : double-_delayedActorList : LinkedList-_mutationsPending : boolean-_simulationUntimed : boolean

IOPort

ProcessDirector

0..1

0..n

controls

0..n

1..1

creates for conditional rendezvous

performs conditional rendezvous for

1..10..n contains

1..1

0..n

contained

contains

FIGURE 5. Static structure diagram for classes in the CSP kernel.

8 of 33 Ptolemy II

Page 15: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

BooleanMatrixTokenBooleanTokenComplexMatrixTokenComplexTokenDoubleMatrixTokenDoubleTokenIntMatrixTokenIntTokenLongMatrixTokenLongTokenObjectTokenStringToken

FIGURE 6. Tokens available in ptolemy.data package.

Masters Report 9 of 33

Page 16: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

s thatesses isp-

g on

PAc-

state-g fromIF.tes thee identi-

4. Using the CSP domain in Ptolemy II

For a model to have CSP semantics, it must have a CSPDirector controlling it. This ensurethe receivers in the ports are CSPReceivers, so all communication of messages between procvia rendezvous. Note that eachactor in the CompositeActor under the control of the CSPDirector reresents a separateprocess in the model.

4.1 RENDEZVOUS

Since the ports contain CSPReceivers, the basic communication statementssend(channel, token)and get(channel)will have rendezvous semantics. Thus the fact that a rendezvous is occurrinevery communication is transparent to the actor code.

4.2 CONDITIONAL COMMUNICATION CONSTRUCTS

In order to use the conditional communication constructs, an actor must be derived from CStor. There are three steps involved:

1) Create a ConditionalReceive or ConditionalSend branch for each guarded communicationment, depending on the communication. Pass each branch a unique integer identifier, startinzero, when creating it. The identifiers only need to be unique within the scope of that CDO or C

2) Pass the branches to the chooseBranch() method in CSPActor. This method evaluaguards, and decides which branch gets to rendezvous, performs the rendezvous and returns thfication number of the branch that succeeded. If all of the guards were false, -1 is returned.

3) Execute the statements for the guarded communication that succeeded.

boolean continueCDO = true;while (continueCDO) {

// step 1:ConditionalBranch[] branches = new ConditionalBranch[#branchesRequired];// Create a ConditionalReceive or a ConditionalSend for each branch// e.g. branches[0] = new ConditionalReceive( (guard), input, 0, 0);

// step 2:int result = chooseBranch(branches);

// step 3:if (result == 0) {

// execute statements associated with first branch} else if (result == 1) {

// execute statements associated with second branch.} else if ... // continue for each branch ID

} else if (result == -1) {// all guards were false so exit CDO.continueCDO = false;

} else {

FIGURE 7. Template for executing a CDO construct.

10 of 33 Ptolemy II

Page 17: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

ed ins, theannel toh. Themuni-

munica-e Tokenard is

A sample template for executing a CDO is shown in figure 7. The code for the buffer describfigure 7 is shown in figure 8. In creating the ConditionalSend and ConditionalReceive branchefirst argument represents the guard. The second and third arguments represent the port and chsend or receive the message on. The fourth argument is the identifier assigned to the brancchoice of placing the guard in the constructor was made to keep the syntax of using guarded comcation statements to the minimum, and to have the branch classes resemble the guarded comtion statements they represent as closely as possible. This can give rise to the case where thspecified in a ConditionalSend branch may not yet exist, but this has no effect as once the gufalse, the token in a ConditionalSend is never referenced.

boolean guard = false;boolean continueCDO = true;ConditionalBranch[] branches = new ConditionalBranch[2];while (continueCDO) {

// step 1guard = (_size < depth);branches[0] = new ConditionalReceive(guard, input, 0, 0);guard = (_size > 0);branches[1] = new ConditionalSend(guard, output, 0, 1, _buffer[_readFrom]);

// step 2int successfulBranch = chooseBranch(branches);

// step 3if (successfulBranch == 0) {

_size++;_buffer[_writeTo] = branches[0].getToken(); _writeTo = ++_writeTo % depth;

} else if (successfulBranch == 1) {_size--;_readFrom = ++_readFrom % depth;

} else if (successfulBranch == -1) { // all guards false so exit CDO

// Note this cannot happen in this case continueCDO = false; } else { throw new TerminateProcessException(getName() + ": " + "branch id returned during execution of CDO."); }}

FIGURE 8. Code used to implement the buffer process described in figure .

Masters Report 11 of 33

Page 18: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

op isvolvedw the

on-very

lainedm the. The

elf foruiva-

etCur-es areo a timeich is

ile it isl time,nce.

notcution

The other option considered was to wrap the creation of each branch as follows:

if (guard) {// create branch and place in branches array

} else {// branches array entry for this branch is null

}

However this leads to longer actor code and what is happening is not as syntactically obvious.The code for using a CIF is similar to the that in figure 7 except that the surrounding while lo

omitted and the case when the identifier returned is -1 does nothing. At some stage the steps inin using a CIF or a CDO may be automated using a pre-parser, but for now the user must folloapproach described above.

It is worth pointing out that if most channels in a model are buffered, it may be worthwhile csidering implementing the model in the PN domain which implicitly has an unbounded buffer on echannel.

4.3 TIME

If a process wishes to use time, the actor representing it must derive from CSPActor. As expin section 2.4, each process in the CSP domain is able to delay itself, either for some period frocurrent model time or until the next occasion time deadlock is reached at the current model timetwo methods to call are delay(double) and waitForDeadlock(). Recall that if a process delays itszero time from the current time, the process will continue immediately. Thus delay(0.0) is not eqlent to waitForDeadlock()

If no processes are delayed, it is also possible to set the model time by calling the method srentTime(newTime) on the director. However, this method can only be called when no processdelayed, as the state of the model may be rendered meaningless if the model time is advanced tbeyond the earliest delayed process. It is primarily for composing CSP with other domains, whexplained below in section 10.1.

As mentioned in section 2.4, as far as each process is concerned, time can only increase whblocked waiting to rendezvous or when delaying. A process can be aware of the current modebut it should only ever affect the model time by delaying its execution, thus forcing time to advaThe method setCurrentTime(newTime) should never be called from a process.

By default every model in the CSP domain is timed. To use CSP without a notion of time, douse the delay(double) method. The infrastructure supporting time does not affect the model exeif the delay(double) method is not used.

12 of 33 Ptolemy II

Page 19: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

rt aSecond,se and

alsoefire()r is anr until

umptionmain-

omain

ishediting

5. Model setup and control

The job of the CSPDirector in controlling the model is two fold. First, it must create and stathread for each actor under its control. Each of these threads represents a process in our model.it is responsible for detecting and responding to both real and time deadlocks. It can also pauresume the model, and terminate all the processes when real deadlock is detected.

5.1 STARTING THE MODEL

The director creates a thread for each actor under its control in its initialize() method. Itinvokes the initialize() method on each actor at this time. The director starts the threads in its prmethod, and detects and responds to deadlocks in its fire() method. The thread for each actoinstance of ProcessThread, which invokes the prefire(), fire() and postfire() methods for the actoit finishes or is terminated. It then invokes the wrapup() method and the thread dies.

Figure 10 shows the code executed by the ProcessThread class. Note that it makes no assabout the actor it is executing, so it can execute any domain-polymorphic actor as well as CSP dospecific actors. In fact any other domain actor that does not rely on the specifics of its parent dcan be executed in the CSP domain by the ProcessThread.

5.2 DETECTING DEADLOCKS:

For deadlock detection, the director maintains three counts:•the number ofactive processes which are threads that have started but have not yet fin•the number ofblocked processes which is the number of processes that are blocked wa

to rendezvous, and

director.initialize() => create a thread for each actorupdate count of active processes with the directorcall initialize() on each actor

director.prefire() => start the process threads => calls actor.prefire()calls actor.fire()calls actor.postfire()repeat.

director.fire() => handle deadlocks until a real deadlock occurs.

director.postfire() => return a boolean indicating if the execution of the model should continue for another iteration

director.wrapup() => terminate all the processes => calls actor.wrapup()decrease the count of active processes with the director

FIGURE 9. Sequence of steps involved in setting up and controlling the model.

Masters Report 13 of 33

Page 20: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

del

eadlockumberyed, thenat theerwisee andup at

.modelis rela-d dies.es thereased

•the number ofdelayed processes which is the number of processes waiting for time toadvance plus the number of processes waiting for time deadlock to occur at the current motime.

When the number of blocked processes equals the number of active processes, then real dhas occurred and the fire method of the director returns. When the number of blocked plus the nof delayed processes equals the number of active processes, and at least one process is delatime deadlock has occurred. If at least one process is delayed waiting for time deadlock to occurcurrent model time, then the director wakes up all such process and does not advance time. Oththe director looks at its list of processes waiting for time to advance, chooses the earliest onadvances time sufficiently to wake it up. It also wakes up any other processes due to be wokenthe new time. The director checks for deadlock each occasion a process blocks, delays or dies

For the director to work correctly, these three counts need to be accurate at all stages of theexecution, so when they are updated becomes important. Keeping the active count accuratetively simple, the director increase it when it starts the thread, and decreases it when the threaLikewise the count of delayed processes is straightforward: when a process delays, it increascount of delayed processes, and the director keeps track of when to wake it up. The count is decwhen a delayed process resumes.

public void run() {try {

boolean iterate = true;while (iterate) {

// container is checked for null to detect the termination// of the actor.iterate = false;if ((Entity)_actor).getContainer() != null && _actor.prefire()) {

_actor.fire();iterate = _actor.postfire();

}}

} catch (TerminateProcessException t) {// Process was terminated early

} catch (IllegalActionException e) {_manager.fireExecutionError(e);

} finally {try {

_actor.wrapup();} catch (IllegalActionExeption e) {

_manager.fireExecutionError(e);}_director.decreaseActiveCount();

}}

FIGURE 10. Code executed by ProcessThread.run()

14 of 33 Ptolemy II

Page 21: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

urated when

thenhen ank of allzvous,ous, the

eth-

d thenfire()ile loopses the

hannelPro-

o-essEx-

ly anytion ofy, thisr that

ception

rmi-aph inl state.d afterl hasn. It

odel,pause()

has

ed with, pausedr This

However, due to the conditional communication constructs, keeping the blocked count accrequires a little more effort. For a basic send or receive, a process is registered as being blockeit arrives at the rendezvous point before the matching communication. The blocked count isdecreased by one when the corresponding communication arrives. However what happens wactor is carrying out a conditional communication construct? In this case the process keeps tracof the branches for which the guards were true, and when all of those are blocked trying to rendeit registers the process as being blocked. When one of the branches succeeds with a rendezvprocess is registered as being unblocked.

5.3 TERMINATING THE MODEL:

A process can finish in one of two ways: either by returning false in its prefire() or postfire() mods, in which case it is said to have finishednormally, or if it is terminatedearlyby a TerminateProces-sException being thrown. For example, if a source process is intended to send ten tokens anfinish, it would exit its fire() method after sending the tenth token, and return false in its postmethod. This causes the ProcessThread, see figure 10, representing the process, to exit the whand execute the finally clause. The finally clause calls wrapup() on the actor it represents, decreacount of active processes in the director, and the thread representing the process dies.

A TerminateProcessException is thrown whenever a process tries to communicate via a cwhose receiver has itsfinishedflag set to true. When a TerminateProcessException is caught incessThread, the finally clause is also executed and the thread representing the process dies.

To terminate the model, the director sets thefinishedflag in each receiver. The next occasion a prcess tries to send to or receive from the channel associated with that receiver, a TerminateProcception is thrown. This mechanism can also be used in a selective fashion to terminate earprocesses that communicate via a particular channel. When the director controlling the executhe model detects real deadlock, it returns from its fire() method. In the absence of hierarchcauses the wrapup() method of the director to be invoked. It is the wrapup() method of the directosets the finished flag in each receiver. Note that the TerminateProcessException is a runtime exso it does not need to be declared as being thrown.

There is also the option of abruptly terminating all the processes in the model by calling tenate() on the director. This method differs from the approach described in the previous paragrthat it stops all the threads immediately and does not give them a chance to update the modeAfter calling this method, the state of the model is unknown and so the model should be recreatecalling this method. This method is only intended for situations when the execution of the modeobviously gone wrong, and for it to finish normally would either take too long or could not happeshould rarely be called.

5.4 PAUSING/RESUMING THE MODEL

Pausing and resuming a model does not affect the outcome of a particular execution of the monly the rate of progress. The execution of a model can be paused at any stage by calling themethod on the director. This method is blocking, and will only return when the model executionbeen successfully paused. To pause the execution of a model, the director sets apausedflag in everyreceiver, and the next occasion a process tries to send to or receive from the channel associatthat receiver, it is paused. The whole model is paused when all the active processes are delayedor blocked. To resume the model, the resume() method can similarly be called on the directo

Masters Report 15 of 33

Page 22: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

er lock.se and

method resets the paused flag in every receiver and wakes up every process waiting on a receivIf a process was paused, it sees that it is no longer paused and continues. The ability to pauresume the execution of a model is intended primarily for user interface control.

16 of 33 Ptolemy II

Page 23: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

of the

to bet dead-

readimulta-nitor

th that

ecifiedcquirelocks,an lead

ad canthe

h thatact in

ckse code

fyAll()

6. Controlling communication between Threads

6.1 BRIEF INTRODUCTION TO THREADS IN JAVA

The CSP domain, like the rest of Ptolemy II, is written entirely in Java and takes advantagefeatures built into the language. In particular, the CSP domain depends heavily onthreadsand onmon-itors for controlling the interaction between threads. In any multi-threaded environment, care hastaken to ensure that the threads do not interact in unintended ways, and that the model does nolock. Note deadlock in this sense is a bug in themodeling environment, which is different from thedeadlock talked about before which may or may not be a bug in themodel being executed.

A monitor is a mechanism for ensuring mutual exclusion between threads. In particular if a thhas a particular monitor, acquired in order to execute some code, then no other thread can sneously have that monitor. If another thread tries to acquire that monitor, it stalls until the mobecomes available. A monitor is also called alock, and one is associated with every object in Java.

Code that is associated with a lock is defined by thesynchronizedkeyword. This keyword caneither be in the signature of a method, in which case the entire method body is associated wilock, or it can be used in the body of a method using the syntax:

synchronized(object) {// synchronized code goes here

}

This causes the code inside the brackets to be associated with the lock belonging to the spobject. In either case, when a thread tries to execute code controlled by a lock, it must either athe lock or stall until the lock becomes available. If a thread stalls when it already has somethose locks are not released, so any other threads waiting on those locks cannot proceed. This cto deadlock when all threads are stalled waiting to acquire some lock they need.

A thread can voluntarily relinquish a lock when stalling by callingobject.wait()whereobjectis theobject to relinquish and wait on.This causes the lock to become available to other threads. A threalso wake up any threads waiting on a lock associated with an object by calling notifyAll() onobject. Note that to issue a notifyAll() on an object it is necessary to own the lock associated witobject first. By careful use of these methods it is possible to ensure that threads only interintended ways and that deadlock does not occur.

6.1.1 Approaches to locking used in the CSP domain

One of the key coding patterns followed is to wrap each wait() call in a while loop that chesome flag. Only when the flag is set to false can the thread proceed beyond that point. Thus thwill often look like

synchronized(object) {...while(flag) {

object.wait();}...

}

The advantage to this is that it is not necessary to worry about what other thread issued the notion the lock; the thread can only continue when the notifyAll() is issuedand the flag has been set tofalse.

Masters Report 17 of 33

Page 24: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

ssible,y muste order.

hreadslocks,m[10].

cquireisSPing the. Thisf the

ure thet pro-

ith thelgo-processnel canrrently

nkes thetrollingat putes at a

Another approach used is to keep the number of locks acquired by a thread as few as popreferably never more than one at a time. If several threads share the same locks, and theacquire more than one lock at some stage, then the locks should always be acquired in the samTo see how this prevent deadlocks, consider two threads,thread1andthread2, that are using two locksA and B. If thread1obtains A first, then B, andthread2obtains B first then A, then a situation couldarise wherebythread1owns lock A and is waiting on B, andthread2owns lock B and is waiting on A.Neither thread can proceed and so deadlock has occurred. This would be prevented if both tobtained lock A first, then lock B. This approach is sufficient, but not necessary to prevent deadas other approaches may also prevent deadlocks without imposing this constraint on the progra

Finally, deadlock often occurs even when a thread, which already has some lock, tries to aanother lock only to issue a notifyAll() on it. To avoid this situation, it is easiest if the notifyAll()issued from anew threadwhich has no locks that could be held if it stalls. This is often used in the Cdomain to wake up any threads waiting on receivers, for example after a pause or when terminatmodel. The class NotifyThread, in the ptolemy.actor.process package, is used for this purposeclass takes a list of objects in a linked list, or a single object, and issues a notifyAll() on each oobjects from within a new thread.

The CSP domain kernel makes extensive use of the above patterns and conventions to ensmodeling engine is deadlock free. However for a much more thorough introduction to concurrengramming Java, a very good starting point is [10].

6.2 RENDEZVOUS ALGORITHM

In CSP, thelocking pointfor all communication between processes is thereceiver. Any occasion aprocess wishes to send or receive, it must first acquire the lock for the receiver associated wchannel it is communicating over. Two key facts to keep in mind when reading the following arithms are that each channel has exactly one receiver associated with it and that at most onecan be trying to send to (or receive from) a channel at any stage. The constraint that each chanhave at most one process trying to send to (or receive from) a channel at any stage is not cuenforced, but an exception will be thrown if such a model is not constructed.

The rendezvous algorithm isentirely symmetricfor the put() and the get(), except for the directiothe token is transferred. This helps reduce the deadlock situations that could arise and also mainteraction between processes more understandable and easier to explain. The algorithm conhow a get() proceeds is shown in figure 11. The algorithm for a put() is exactly the same except thand get are swapped everywhere. Thus it suffices to explain what happens when a get() arrivreceiver i.e. when a process tries to receive from the channel associated with the receiver.

18 of 33 Ptolemy II

Page 25: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

Bothimulta-ume aa put()

When a get() arrives at a receiver, a put() is either already waiting to rendezvous or it isn’t.the get() and put() methods are entirely synchronized on the receiver so they cannot happen sneously (only one thread can possess a lock at any given time). Without loss of generality assget() arrives before a put(). The rendezvous mechanism is basically three steps: a get() arrives,arrives, the rendezvous completes.

get arrives

put waiting? get waiting = trueNo

notifyAll

_checkAndWaitget

waiting?

register actorblocked

register actorunblocked

rendezvouscomplete = true

notifyAll

No

Yes

put waiting = false

rendezvouscomplete = false

_checkAndWait

notifyAll

rendezvouscomplete?

No

Yes

Wakes upCondSend if oneis waiting

Yes

wakes up

wakes up

FIGURE 11. Rendezvous algorithm

Masters Report 19 of 33

Page 26: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

its on

the put

ezvousakingcessaryt, except

thethe geteiver.en the

anch

a newl thesethreadsscribede con-unica-designs prone

(1) When the get arrives it sees that it is first and sets a flag saying a get is waiting. It then wathe receiver lock while the flag is still true,(2) When a put arrives, it sets thegetWaitingflag to false,wakes up any threads waiting on the receiver (including the get), sets therendezvousCompleteflag tofalse and then waits on the receiver while therendezvousCompleteflag is false,(3) The thread execut-ing the get wakes up, sees that a put has arrived, sets therendezvousCompleteflag to true, wakes upany threads waiting on the receiver and returns thus releasing the lock. The thread executingthen wakes up, acquires the receiver lock, sees that the rendezvous is complete and returns.

Following the rendezvous, the state of the receiver is exactly the same as before the rendarrived, and it is ready to mediate another rendezvous. It is worth noting that the final step, of msure the second communication to arrive does not return until the rendezvous is complete, is neto ensure that the correct token gets transferred. Consider the case again when a get arrives firsnow the put returns immediately if a get is already waiting. A put arrives, places a token inreceiver, sets the get waiting flag to false and returns. Now suppose another put arrives beforewakes up, which will happen if the thread the put is in wins the race to obtain the lock on the recThen the second put places a new token in the receiver and sets the put waiting flag to true. Thget wakes up, and returns with the wrong token! This is known as arace condition, which will lead tounintended behavior in the model.

6.3 CONDITIONAL COMMUNICATION ALGORITHM

There are two steps involved in executing a CIF or a CDO: first deciding which enabled brsucceeds, then carrying out the rendezvous.

6.3.1 Built on top of rendezvous:

When a conditional construct has more than one enabled branch (guard is true or absent),thread is spawned for each enabled branch. The job of the chooseBranch() method is to controthreads and to determine which branch should be allowed to successfully rendezvous. Theseand the mechanism controlling them are entirely separate from the rendezvous mechanism dein section 6.2, with the exception of one special case, which is described in section 6.4. Thus thditional mechanism can be viewed as being built on top of basic rendezvous: conditional commtion knows about and needs basic rendezvous, but the opposite is not true. Again this is adecision which leads to making the interaction between threads easier to understand and is lesto deadlock as there are fewer interaction possibilities to consider.

rendezvous

which branch should succeed?

FIGURE 12. Conceptual view of how conditional communication is built on top of rendezvous.

20 of 33 Ptolemy II

Page 27: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

oose-e false,formsrestingh brancht getsll thecessfulully per-

ting a

then the

goesks if iting

checkdition-er andwithtries

nch tofirst to

at thero-r aware

p, itfailede if arancha get. If

6.3.2 Choosing which branch succeeds

The manner in which the choice of which branch can rendezvous is worth explaining. The chBranch() method in CSPActor takes an array of branches as an argument. If all of the guards arit returns -1, which indicates that all the branches failed. If exactly one of the guards is true, it perthe rendezvous directly and returns the identification number of the successful branch. The intecase is when more than one guard is true. In this case, it creates and starts a new thread for eacwhose guard is true. It then waits, on an internal lock, for one branch to succeed. At that point iwoken up, sets a finished flag in the remaining branches and waits for them to fail. When athreads representing the branches are finished, it returns the identification number of the sucbranch. This approach is designed to ensure that exactly one of the branches created successfforms a rendezvous.

6.3.3 Algorithm used by each branch:

Similar to the approach followed for rendezvous, the algorithm by which a thread represenbranch determines whether or not it can proceed is entirelysymmetricalfor a ConditionalSend and aConditionalReceive. The algorithm followed by a ConditionalReceive is shown figure 13. Againlocking point is the receiver, and all code concerned with the communication is synchronized oreceiver. The receiver is also where all necessary flags are stored.

Consider three cases.(1) a conditionalReceive arrives and a put is waiting.In this case, the branch checks if it is the first branch to be ready to rendezvous, and if so, it is

ahead and executes a get. If it is not the first, it waits on the receiver. When it wakes up, it checis still alive. If it is not, it registers that it has failed and dies. If it is still alive, it starts again by tryto be the first branch to rendezvous. Note that a put cannot disappear.

(2) a conditionalReceive arrives and a conditionalSend is waitingWhen both sides are conditional branches, it is up to the branch that arrives second to

whether the rendezvous can proceed. If both branches are the first to try to rendezvous, the conalReceive executes a get(), notifies its parent that it succeeded, issues a notifyAll() on the receivdies. If not, it checks whether it has been terminated by chooseBranch(). If it has, it registerschooseBranch() that it has failed and dies. If it has not, it returns to the start of the algorithm andagain. This is because a ConditionalSend could disappear. Note that the parent of the first braarrive at the receiver needs to be stored for the purpose of checking if both branches are thearrive.

This part of the algorithm is somewhat subtle. When the second conditional branch arrivesrendezvous point it checks thatboth sides are the first to try to rendezvous for their respective pcesses. If so, then the conditionalReceive executes a get(), so that the conditionalSend is nevethat a conditionalReceive arrived: it only sees the get().

(3) a conditionalReceive arrives first.It sets a flag in the receiver that it is waiting, then waits on the receiver. When it wakes u

checks if it has been killed by chooseBranch. If it has it registers with chooseBranch that it hasand dies. Otherwise it checks if a put is waiting. It only needs to check if a put is waiting becausconditionalSend arrived, it would have behaved as in case (2) above. If a put is waiting, the bchecks if it is the first branch to be ready to rendezvous, and if so it is goes ahead and executes

Masters Report 21 of 33

Page 28: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

condi-gisterend isstered

ge to

it is not the first, it waits on the receiver and tries again.

6.4 MODIFICATION OF RENDEZVOUS ALGORITHM:

Consider the case when a conditional send arrives before a get. If all the branches in thetional communication which the conditional send is a part of are blocked, then the process will reitself as blocked with the director. Then the get comes along, and even though a conditional swaiting, it too would register itself as blocked. This leads to one too many processes being regias blocked, which could lead to premature deadlock detection.

To avoid this, it is necessary to modify the algorithm used for rendezvous slightly. The chan

conditional receivearrives

put waiting? No

get!!branchSucceeded

Yes

conditionalsend waiting?

first branch torendezvous?

Yes

branchFailed No

Return

_checkAndWait

NoReturn

still alive?

a put cannotdissappear

Yesfirst branch torendezvous?

_checkAndWaitNo

a conditionalSendCAN dissappear

Yes

still alive?

Yes

other sidefirst branch torendezvous?

notifyAllNo

No

Yes

get!!branchSucceeded

Return

No

conditional receivewaiting = true

_checkAndWait

branchFailed No

Return

still alive?

Yes

put waiting?get!!

branchSucceededYes

Return

No

Yes

branchFailed No

Return

Case 1 Case 2Case 3

first branch torendezvous?

Yes

No

FIGURE 13. Algorithm used to determine if a conditional rendezvous branch succeeds or fails

22 of 33 Ptolemy II

Page 29: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

in thess thatndi-al sendous. IfAll()

r before

the algorithm is shown in the dashed ellipse in figure 14. It does not affect the algorithm exceptcase when a conditional send is waiting when a get arrives at the receiver. In this case the procecalls the get should wait on the receiver until the conditional send waiting flag is false. If the cotional send succeeded, and hence executed a put, then the get waiting flag and the conditionwaiting flag should both be false and the actor proceeds through to the third step of the rendezvthe conditional send failed, it will have reset the conditional send waiting flag and issued a notifyon the receiver, thus waking up the get and allowing it to properly wait for a put.

The same reasoning also applies to the case when a conditional receive arrives at a receivea put.

FIGURE 14. Modification of rendezvous algorithm, section 6.4, shown in ellipse

get waiting = true

notifyAll

_checkAndWaitget

waiting?

register actorblocked

register actorunblocked

No

Yes

_checkAndWaitconditionalsend waiting?

No

Yes

Masters Report 23 of 33

Page 30: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

onalood inds bothhile,

uts thebeing. This

can eat

assicming:

s can

rs

psticker andused by

aitings nextinter-ssagestained

se it,absencelock

7. Demos and Examples

7.1 DINING PHILOSOPHERS.

This implementation of the Dining Philosophers problem illustrates both time and conditicommunication in the CSP domain. Five philosophers are seated at a table with a large bowl of fthe middle. Between each pair of philosophers is one chopstick, and to eat, a philosopher neethe chopsticks beside him. Each philosopher spends his life in the following cycle: thinks for a wgets hungry, picks up one of the chopsticks beside him, then the other, eats for a while and pchopsticks down on the table again. If a philosopher tries to grab a chopstick but it is alreadyused by another philosopher, then the philosopher waits until that chopstick becomes availableimplies that no neighboring philosophers can eat at the same time and at most two philosophersat a time.

The Dining Philosophers problem was first dreamt up by Edsger W. Dijkstra in 1965. It is a clconcurrent programming problem that illustrates the two basic properties of concurrent program

Liveness.How can we design the program to avoid deadlock, where none of the philosophermake progress because each is waiting for someone else to do something?

Fairness. How can we design the program to avoid starvation, where one of the philosophecould make progress but does not because others always go first?

This implementation uses an algorithm that lets each philosopher randomly chose which choto pick up first (via a CDO), and all philosophers eat and think at the same rates. Each philosopheach chopstick are represented by a separate process. Each chopstick has to be ready to beeither philosopher beside it at any time, hence the use of a CDO. After it is grabbed, it blocks wfor a message from the philosopher that is using it. After a philosopher grabs both the chopstickto him, he eats for a random time. This is represented by calling delay(double) with the randomval to eat for. The same approach is used when a philosopher is thinking. Note that because meare passed by rendezvous, the blocking of a philosopher when it cannot obtain a chopstick is obfor free.

This algorithm is fair, as any time a chopstick is not being used, and both philosophers try to uthey both have an equal chance of succeeding. However this algorithm does not guarantee theof deadlock, and if it is let run long enough this will eventually occur. The probability that deadoccurs sooner increases as the thinking times are decreased relative to the eating times.

= chopstick

= philosopher

FIGURE 15. Illustration of the Dining Philosophers problem

24 of 33 Ptolemy II

Page 31: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

val of, and theat the

e ratesariousd and

r could

ame asoon as(). Themodelor the

ed in

7.2 M/M/1

This demo illustrates a simple M/M/1 queue. It has three actors, one representing the arricustomers, one for the queue holding customers that have arrived and have not yet been servedthird representing the server. Both the inter-arrival times of customers and the service timesserver are exponentially distributed, which of course is what makes this a M/M/1 queue.

FIGURE 16. Actors involved in M/M/1 demo

This demo makes use of basic rendezvous, conditional rendezvous and time. By varying thfor the customer arrivals and service times, and varying the length of the buffer, you can see vtrade-offs. For example if the buffer length is too short, customers may arrive that cannot be storeso are missed. Similarly if the service rate is faster than the customer arrival rate, then the servespend a lot of time idle.

7.3 PAUSING M/M/1

This example demonstrates how pausing and resumption works. The setup is exactly the sin the M/M/1 demo, except that the thread executing the model calls pause() on the director as sthe model starts executing. It then waits two seconds, as arbitrary choice, and then calls resumepurpose of this demo is to show that the pausing and resuming of a model does not affect theresults, only its rate of progress. The ability to pause and resume a model is primarily intended fuser interface.

7.4 SIEVE OF ERATOSTHENES

This demo illustrates changes to the topology during the execution of a model. It is explaindetail in the section on topology changes, section 8.2.

servercustomersarriving

buffer

Masters Report 25 of 33

Page 32: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

rse ofl exe-

havecontin-ucing

t cre-must bet anythe pro-ock().This istopology

ceivery thatzvous

thisezvous

process

nts thelly in asing ane ideacessed,e made

that

ed dur-tion in

ut allo filtermbere sieve

8. Changes to the Topology during the Execution of a Model

For some models it may be necessary to change the topology of the model during the couexecuting the model. This is supported in the CSP domain, but only at specific points of the modecution. In particular, changes to the topology are only allowed at deadlock points.

When the director detects deadlock, real or timed, it then checks if any topology changesbeen queued with it. If one or more topology change has been queued, it carries them out andues. Note that the result of a topology change might remove an otherwise real deadlock by introdnew processes.

8.1 HOW TO WRITE AN ACTOR THAT USES TOPOLOGY CHANGES

The procedure for making a topology change is relatively straightforward. First the actor musate a TopologyChangeRequest object representing the topology change. Second, the requestqueued with the director by calling queueTopologyChange(). If the topology change will not affecchannels or ports the process is communicating with, then the process can proceed. Otherwisecess should delay itself until the next occasion a time deadlock occurs by calling waitForDeadlThen, when the process wakes up again, the director will already have performed the mutation.because topology changes get processed when a deadlock is detected, and any queuedchanges are done before waking up delayed processes or advancing time.

The reason for delaying is that it is important that no process be waiting to rendezvous at a rein a port affected by the topology change. When a port is affected by a topology change, it is likelit will abandon its old receivers and create new ones. This will leave the process trying to rendewith a dangling receiver, which will eventually cause the model to terminate early. To get aroundproblem, it is necessary to delay the execution of any processes that may be affected by a renduntil the next occasion a time deadlock occurs. For example in the CSPSieve process, eachcalls waitForDeadlock() immediately after queueing the mutation.

To create a TopologyChangeRequest, it is necessary to create a subclass that implemeabstract method constructEventQueue(). This is most easily done using an inner class, normaprivate method of the actor. The code in CSPSieve contains an example of this. The reason for uinner class with a method that creates the topology change is to avoid potential deadlocks. Thbehind avoiding the deadlocks is that the topology changes only happen when the request is prowhich is when the constructEventQueue() method gets invoked. Thus the topology changes arfrom within the thread that the director is running in, and not the thread running the processrequested the change.

For a more detailed explanation of how changes to the topology are constructed and executing the execution of a model, and the changes that are allowed, try reading the appropriate secthe Ptolemy II design document[13].

8.2 SIEVE OF ERATOSTHENES EXAMPLE

This example implements theSieve of Eratosthenes. It is an algorithm for generating a list ofprime numbers. It originally consists of a source generating integers, and one sieve filtering omultiples of two. When the end sieve sees a number that it cannot filter, it creates a new sieve tout all multiplies of that number. Thus after the sieve filtering out the number two sees the nuthree, it creates a new sieve that filters out the number three. This then continues with the thre

26 of 33 Ptolemy II

Page 33: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

ill bell theis cre-

. Eache chain

eventually creating a sieve to filter out all multiples of five, and so on. Thus after a while there wa chain of sieves each filtering out a different prime number. If any number passes through asieves and reaches the end with no sieve waiting, it must be another prime and so a new sieveated for it.

This demo is an example of how changes to the topology can be made in the CSP domaintopology change here involves creating a new CSPSieve actor and connecting it to the end of thof sieves.

2

3

3

4

5

55

printer ramp

sieve(2)

sieve(3)

7

6

7

77

sieve(5)

8

9

9

10

11

11

11

11

12

sieve(7)

11sieve(11)13

13

13

13

1313

FIGURE 17. Illustration of Sieve of Eratosthenes for obtaining first six primes.

Masters Report 27 of 33

Page 34: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

f thef thesef CSPed ind otherP with

an iter-to thewhen

e and

com-he out-threade beenn inputdez-

el uphes toon each

output

n theinputs

9. Composing CSP with other domains

In Ptolemy the mixing of domains is achieved through the use of hierarchy. At any level ohierarchy, all the actors obey the same semantics (model of computation), but inside any one oactors there may be another domain using a different model of computation. The composition owith other domains has not yet been fully explored, but a considerable amount of the effort involvdesigning the domain was aimed at ensuring smooth interaction between the CSP domain andomains. In this chapter I have placed some of the thoughts that may be useful in composing CSother domains.

9.1 CSP INSIDE ANOTHER DOMAIN

In this case, real deadlock no longer ends the model execution, but instead marks the end ofation one level up in the hierarchy. The director transfers any tokens from the inside CSP domainoutside domain. Control then returns to the outside domain, which continues its execution. Thenfire() is called again on the CSPDirector it transfers any inputs from the outside domain insidcontinues until real deadlock is reached again.

The transferring of inputs from the outside domain and inside domain should probably be acplished using a separate TransferThread object. These threads would simply get a Token from tside domain, and send it to the channel inside the CSP model. This would be repeated until theblocks because there are no more Tokens at the outside level, or when “enough” tokens havtransferred. The director would create one of these threads for each channel that represents afrom one level up in the hierarchy. The director thread will not block as it is not performing the renvous directly.

Similarly, when the director is transferring outputs from the CSP model to the model one levin the hierarchy, it also creates a TransferThread to perform the transfer. If the CSP model wistransfer more than one message per iteration up the hierarchy, a CSPBuffer should be placedoutput channel that transfers more than one message. This is to allow the process sending to thechannel to continue after sending the first message.

For example if a CSP domain inside a CompositeActor is represented by figure 18(a), theCSP model inside might have the form shown in (b). The dashed arrows show the transfer of

2

32

2

(a) (b)

FIGURE 18. Exploded view of what a CSP subsystem might look like inside a compositeactor in another domain.

28 of 33 Ptolemy II

Page 35: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

ows theitera-

l pro-l execu-shownut thel of pro-process

l be toesses

0. Dueth thel one

is upalsot to theinput

and outputs between the two levels of the hierarchy.Each occasion real deadlock occurs, it is guaranteed that no processes are delayed. This all

time for the CSP model to be set, by the director one level up in the hierarchy, at the start of eachtion. This should make composing CSP with other timed domains reasonably straightforward.

9.1.1 CSP within CSP

The CSP model of computation is not compositional. This means that composing severacesses into a single process one level up in the hierarchy may impact the semantics of the modetion. To see this, consider two processes that each simply read an input, then send it on. This isin figure 19. If a stream of messages is sent along the input channel of process A, then it will outpsame stream of messages on its output channel. No messages are sent along the input channecess B. If the two processes are then composed as shown by the dashed box, and the composedreads alternately from the two input channels, then the behavior of the composed process wilblock waiting for a message on the second channel, which is different from that of the two procseparately.

9.2 ANOTHER DOMAIN INSIDE CSP

Recall that each actor in a CSP model is executed by a ProcessThread, as shown in figure 1to the semantics of the CSP model of computation, the inside model is executed in parallel wiother processes. This has implications for the availability of Tokens at the input ports of the modelevel down in the hierarchy. If the inside model requires a certain set of Tokens in order to fire, itto the director controlling the inside model to ensure this before it executes. This director isresponsible for obtaining any Tokens at each CSPReceiver so that another Token could be senreceiver if necessary. This is how the inside domain acquires more than one Token on any givenchannel.

A

B

FIGURE 19. Example showing how CSP is not compositional

Masters Report 29 of 33

Page 36: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

he key

d waseach

, if noof ane timehierar-

disad-or.

ility.r con-

ved,ve to bentrol-ion of

re isk sim-these

ollingn actor

nchro-

s areakinginterac-ation

echa-

10. Design decisions

In designing the CSP domain, many design choices had to be made. Below are some of tdesign decisions that were made and the motivation for the implementation chosen.

10.1 TIME: DISTRIBUTED RELATIVE TIME VERSUS CENTRALIZED ABSOLUTE TIME

One of the key decisions that had to be made was what model of time to use. The model usechosen primarily to make composing CSP domains with other timed domains possible. Sinceactor only deals with delays relative to the current model time, or at the current model time, thenactors are delayed, the current model time can be arbitrarily set. This works well with the notioniteration in CSP which is when real deadlock is reached, i.e. when no actors are delayed. Thus thof a CSP subsystem could be set at the start of each iteration by the director one level up in thechy.

The model also has the added advantage that it is relatively simple and easy to use. The onlyvantage is that time is centralized and so all actions involving time must pass through the direct

10.2 CHOICE OF LOCKS USED AND LOCKING POINTS

The receiver is chosen as the locking point for all communications primarily for scalabBecause the processes involved in a rendezvous lock locally on the receiver involved, the directotrolling the model is not directly involved in mediating any rendezvous. If the director were involthen as the models became larger the performance would suffer as each rendezvous would hacarried out through the director. The receiver is a natural point for storing the flags involved in coling a conditional communication. Note that a rendezvous is completely separate from the nottime in the domain.

There are three primary lock types in use in the CSP domain: the director lock, of which theonly one, a lock for each receiver, and an internal lock hidden inside each actor. The hidden locply takes the place of locking on the actor for internal control mechanisms. The use of each oflocks should not be visible when using the domain. The decision to use an internal lock for contraccess to methods of CSPActor was made to avoid using any lock that the code in a user writtemight use. In particular, the actor code should be able tolock on itself.If we had chosen to lock ontothe actor itself, as opposed to a hidden lock, then the model could deadlock if the actor code synized on itself.

10.3 MAKING ALL THE COMMUNICATION MECHANISMS SYMMETRIC

Aside from the fact that a Token is transferred or received in a rendezvous, the two actionsymmetric, so I felt that the locking algorithms should also be. This also has the advantage of mthe algorithm easier to understand and less prone to unintended deadlocks as there are fewertions to consider. Similarly the choice of making the algorithm used in the guarded communicthreads symmetric is made to keep it as simple, understandable and as robust as possible.

10.4 CONDITIONAL COMMUNICATION MECHANISMS UPON RENDEZVOUS

The reason for building the conditional communication mechanism upon the rendezvous m

30 of 33 Ptolemy II

Page 37: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

ecideoving

nts, oronly at

of theor arelocks

d whene model

e rateas theodel.

ructs,

nism is that it is logically clearer what is happening when it is separated into two steps: first dwhich branch will rendezvous, then do the rendezvous. This also enables tracking down and remsituations where false deadlocks could arise.

10.5 POINTS IN THE MODEL WHEN CHANGES TO THE TOPOLOGY ARE ALLOWED

The options considered for when to allow changes to the topology are either at deadlock poias soon as the model can be paused. The reason for choosing to allow changes to the topologydeadlock points is mainly that these points are intrinsic to the nature of the model. The statemodel is well defined at these points: all processes are either blocked trying to communicatedelayed waiting for time to advance. For any execution of a model, the times at which time deadoccur are the times at which topology changes may occur. This allows for a process to be createanother process reaches some state, and the two processes will be continuing from the samtime.

Pausing and resuming a model does not affect the outcome of a particular model run, only thof progress. Thus if changes to the topology were allowed to happen immediately (as soonmodel is able to pause), this would result in a new nondeterminism being introduced into the mFor CSP we wish to keep all nondeterminism the result of the conditional communication constso topology changes are only allowed at deadlocks.

Masters Report 31 of 33

Page 38: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

lt intoems atdel toe CSPstent

tems.herember of

t yetnsur-some

ettables usedodify

11. Conclusion and Future Work

The CSP domain in Ptolemy II has been implemented using the concurrency support buiJava. It builds upon the low level support Java offers to allow the user to design concurrent systa much higher level of abstraction. A notion of time has been added to the classical CSP moenable modeling of systems where time is relevant, in particular embedded systems. Finally, thdomain allows the topology of a model to change during execution while still maintaining a consistate.

The composition of CSP with other domains is important for heterogeneous modeling of sysIn particular it is envisioned that the CSP domain will be hierarchically composed in models wresource contention is a major concern. Some examples include embedded systems where a nufunctions share the same CPU, or in modeling client/server architectures.

The hierarchical composition of the CSP domain with other domains in Ptolemy II has nobeen fully explored. However, much of the effort in designing the CSP domain was devoted to eing that the CSP domain could be successfully composed with other domains. It should make forvery interesting research defining and exploring the semantics of these interactions. It is regrthat I did not have enough time to start exploring this area. I believe the design and the algorithmin the domain are sufficiently adaptable/clear that the domain should be fairly easy to extend or mif necessary.

32 of 33 Ptolemy II

Page 39: COMMUNICATING SEQUENTIAL PROCESSES …ptolemy.eecs.berkeley.edu/publications/papers/98/CSPin...The Communicating Sequential Processes (CSP) domain in Ptolemy II models a system as

LA

.

95.

References

[1] G. R. Andrews,Concurrent Programming - Principles and Practice, Addison-Wesley, 1991.

[2] A. Burns,Programming in OCCAM 2, Addison-Wesley, 1988.

[3] P. H. J. van Eijk, C. A. Vissers, M. Diaz,The formal description technique LOTOS, Elsevier Sci-ence, B.V., 1989. (http://wwwtios.cs.utwente.nl/lotos)

[4] M. Fowler and K. Scott,UML Distilled, Addison-Wesley, 1997.

[5] A.J.C. van Gemund,“Performance Prediction of Parallel Processing Systems: The PAMEMethodology,” Proc. 7th Int. Conf. on Supercomputing, pages 418-327, Tokyo, July 1993.

[6] M. G. Hinchey and S. A. Jarvis,Concurrent Systems: Formal Developments in CSP, McGraw-Hill, 1995.

[7] C. A. R. Hoare,“Communicating Sequential Processes,”Communications of the ACM, Vol. 21,No. 8, August 1978.

[8] C. A. R. Hoare,Communicating Sequential Processes, Prentice-Hall, 1985.

[9] G. Kahn, “The Semantics of a Simple Language for Parallel Programming,”Proc. of the IFIPCongress 74, North-Holand Publishing Co., 1974.

[10] D. Lea,Concurrent Programming in JavaTM, Addison-Wesley, MA, 1997.

[11] E. A. Lee and T. M. Parks,“Dataflow Process Networks,”Proceedings of the IEEE, vol. 83, no5, pp. 773-801, May, 1995. (http://ptolemy.eecs.berkeley.edu/papers/processNets)

[12] T. M. Parks,Bounded Scheduling of Process Networks, Technical Report UCB/ERL-95-105.Ph.D. Dissertation. EECS department, University of California, CA 94720, December 19http://ptolemy.eecs.berkeley.edu/papers/parksThesis)

[13] The Ptolemy Project,PtolemyII, http://ptolemy.eecs.berkeley.edu/ptolemyII.

Masters Report 33 of 33