ptolemy.domains.csp.kernel
Class CSPDirector

java.lang.Object
  extended by ptolemy.kernel.util.NamedObj
      extended by ptolemy.kernel.util.Attribute
          extended by ptolemy.actor.Director
              extended by ptolemy.actor.process.ProcessDirector
                  extended by ptolemy.actor.process.CompositeProcessDirector
                      extended by ptolemy.domains.csp.kernel.CSPDirector
All Implemented Interfaces:
java.io.Serializable, java.lang.Cloneable, Executable, Initializable, TimedDirector, Changeable, Debuggable, DebugListener, Derivable, ModelErrorHandler, MoMLExportable, Moveable, Nameable

public class CSPDirector
extends CompositeProcessDirector
implements TimedDirector

CSPDirector governs the execution of a composite actor with the semantics of the Communicating Sequential Processes (CSP) domain.

In the CSP domain, the director creates a thread for executing each actor under its control. Each actor corresponds to a process in the model. The threads are created in the initialize method and started in the prefire method. After the thread for an actor is started it is active until the thread finishes. While the process is active, it can also be blocked or delayed, but not both. A process is blocked if it is trying to communicate but the process with which it is trying to communicate is not ready to do so yet. A process is delayed if it is waiting for time to advance, or if it is waiting for a deadlock to occur.

The director is responsible for handling deadlocks, both real and timed. It is also responsible for carrying out any requests for changes to the topology that have been made when a deadlock occurs. It maintains counts of the number of active processes, the number of blocked processes, and the number of delayed processes. Deadlock occurs when the number of blocked processes plus the number of delayed processes equals the number of active processes. Time deadlock occurs if at least one of the active processes is delayed. Real deadlock occurs if all of the active processes under the control of this director are blocked trying to communicate. The fire method controls and responds to deadlocks and carries out changes to the topology when it is appropriate.

If real deadlock occurs, the fire method returns. If there are no levels above this level in the hierarchy then this marks the end of execution of the model. The model execution is terminated by setting a flag in every receiver contained in actors controlled by this director. When a process tries to send or receive from a receiver with the terminated flag set, a TerminateProcessException is thrown which causes the actors execution thread to terminate.

Time is controlled by the director. Each process can delay for some delta time, and it will continue when the director has advanced time by that length of time from the current time. A process is delayed by calling delay(double) method. The director advances time each occasion a time deadlock occurs and no changes to the topology are pending. If a process specifies zero delay, then the process continues immediately. A process may delay itself until the next time deadlock occurs by calling waitForDeadlock(). Then the next occasion time deadlock occurs, the director wakes up any processes waiting for deadlock, and does not advance the current time. Otherwise the current model time is increased as well as being advanced. By default the model of computation used in the CSP domain is timed. To use CSP without a notion of time, do not use the delay(double) method in any process.

Changes to the topology can occur when deadlock, real or timed, is reached. The director carries out any changes that have been queued with it. Note that the result of the topology changes may remove the deadlock that caused the changes to be carried out.

Since:
Ptolemy II 0.2
Version:
$Id: CSPDirector.java 57040 2010-01-27 20:52:32Z cxh $
Author:
Neil Smyth, Mudit Goel, John S. Davis II
See Also:
Director, Serialized Form
Accepted Rating:
Green (kienhuis)
Proposed Rating:
Green (nsmyth)

Nested Class Summary
private static class CSPDirector.DelayListLink
          Keep track of the actor that is delayed and the time at which to resume it.
 
Nested classes/interfaces inherited from class ptolemy.kernel.util.NamedObj
NamedObj.ContainedObjectsIterator
 
Field Summary
private  int _actorsDelayed
          Count of the number of processes delayed until time sufficiently advances.
private  java.util.List _delayedActorList
           
private  boolean _inWrapup
           
 
Fields inherited from class ptolemy.actor.process.ProcessDirector
_notDone, _stopFireRequested
 
Fields inherited from class ptolemy.actor.Director
_actorsFinishedExecution, _currentTime, _finishRequested, _initializables, _stopRequested, timeResolution
 
Fields inherited from class ptolemy.kernel.util.NamedObj
_changeListeners, _changeLock, _changeRequests, _debugging, _debugListeners, _elementName, _isPersistent, _verbose, _workspace, ATTRIBUTES, CLASSNAME, COMPLETE, CONTENTS, DEEP, FULLNAME, LINKS
 
Fields inherited from interface ptolemy.actor.Executable
COMPLETED, NOT_READY, STOP_ITERATING
 
Constructor Summary
CSPDirector()
          Construct a director in the default workspace with an empty string as its name.
CSPDirector(CompositeEntity container, java.lang.String name)
          Construct a director in the given container with the given name.
CSPDirector(Workspace workspace)
          Construct a director in the workspace with an empty name.
 
Method Summary
protected  void _actorDelayed(double delta, CSPActor actor)
          Called by a CSPActor when it wants to delay.
protected  boolean _areAllThreadsStopped()
          Return true if the count of active processes equals the number of stopped, blocked, and delayed threads.
protected  boolean _areThreadsDeadlocked()
          Returns true if all active processes are either blocked or delayed, false otherwise.
private  Time _getNextTime()
          Get the earliest time which an actor has been delayed to.
private  java.lang.String _receiverStatus()
          Return a string describing the status of each receiver.
protected static java.lang.String _receiverStatus(Receiver receiver)
          Return a string describing the status of the specified receiver.
private  void _registerDelayedActor(Time actorTime, CSPActor actor)
          Keep track of when and for how long processes are delayed.
protected  boolean _resolveInternalDeadlock()
          Respond to a deadlock.
 java.lang.Object clone(Workspace workspace)
          Clone the director into the specified workspace.
 Dependency delayDependency(double delay)
          Return a boolean dependency representing a model-time delay of the specified amount.
 void initialize()
          Reset flags to initialize values.
 Receiver newReceiver()
          Return a new CSPReceiver compatible with this director.
 boolean postfire()
          Return false if deadlock has occurred and there are no input ports, or if stop() has been called, and true otherwise.
 java.lang.String[] suggestedModalModelDirectors()
          Return an array of suggested directors to be used with ModalModel.
 void wrapup()
          Override the base class to stop any actors that might be stalled in a call to delay().
 
Methods inherited from class ptolemy.actor.process.CompositeProcessDirector
_areActorsExternallyBlocked, _controllerBlocked, _controllerUnBlocked, _isInputControllerBlocked, _isOutputControllerBlocked, _resolveDeadlock, createBranchController, getInputController, getOutputController, prefire, setModelTime, stopInputBranchController, stopOutputBranchController, threadBlocked, threadUnblocked
 
Methods inherited from class ptolemy.actor.process.ProcessDirector
_getActiveThreadsCount, _getBlockedThreadsCount, _getStoppedThreadsCount, _newProcessThread, addThread, finish, fire, initialize, isStopFireRequested, isStopRequested, isThreadActive, preinitialize, removeThread, stop, stopFire, terminate, threadHasPaused, threadHasResumed, transferInputs, transferOutputs
 
Methods inherited from class ptolemy.actor.Director
_description, _fireContainerAt, _isEmbedded, _isTopLevel, _transferInputs, _transferOutputs, addInitializable, attributeChanged, createSchedule, defaultDependency, fireAt, fireAt, fireAtCurrentTime, getCausalityInterface, getCurrentTime, getErrorTolerance, getGlobalTime, getModelNextIterationTime, getModelStartTime, getModelStopTime, getModelTime, getNextIterationTime, getStartTime, getStopTime, getTimeResolution, implementsStrictActorSemantics, invalidateResolvedTypes, invalidateSchedule, isFireFunctional, isStrict, iterate, preinitialize, removeInitializable, requestInitialization, setContainer, setCurrentTime, supportMultirateFiring
 
Methods inherited from class ptolemy.kernel.util.Attribute
_checkContainer, _getContainedObject, _propagateExistence, getContainer, moveDown, moveToFirst, moveToIndex, moveToLast, moveUp, setName, updateContent
 
Methods inherited from class ptolemy.kernel.util.NamedObj
_addAttribute, _adjustOverride, _attachText, _cloneFixAttributeFields, _debug, _debug, _debug, _debug, _debug, _exportMoMLContents, _getIndentPrefix, _isMoMLSuppressed, _markContentsDerived, _propagateValue, _recordDecoratedAttributes, _removeAttribute, _splitName, _stripNumericSuffix, _validateSettables, addChangeListener, addDebugListener, attributeList, attributeList, attributeTypeChanged, clone, containedObjectsIterator, deepContains, depthInHierarchy, description, description, event, executeChangeRequests, exportMoML, exportMoML, exportMoML, exportMoML, exportMoML, exportMoMLPlain, getAttribute, getAttribute, getAttributes, getChangeListeners, getClassName, getDecoratorAttribute, getDecoratorAttributes, getDerivedLevel, getDerivedList, getDisplayName, getElementName, getFullName, getModelErrorHandler, getName, getName, getPrototypeList, getSource, handleModelError, isDeferringChangeRequests, isOverridden, isPersistent, lazyContainedObjectsIterator, message, propagateExistence, propagateValue, propagateValues, removeChangeListener, removeDebugListener, requestChange, setClassName, setDeferringChangeRequests, setDerivedLevel, setDisplayName, setModelErrorHandler, setPersistent, setSource, sortContainedObjects, toplevel, toString, uniqueName, validateSettables, workspace
 
Methods inherited from class java.lang.Object
equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
 
Methods inherited from interface ptolemy.actor.TimedDirector
getModelTime, getTimeResolution
 

Field Detail

_actorsDelayed

private int _actorsDelayed
Count of the number of processes delayed until time sufficiently advances.


_delayedActorList

private java.util.List _delayedActorList

_inWrapup

private boolean _inWrapup
Constructor Detail

CSPDirector

public CSPDirector()
Construct a director in the default workspace with an empty string as its name. The director is added to the list of objects in the workspace. Increment the version number of the workspace.


CSPDirector

public CSPDirector(Workspace workspace)
Construct a director in the workspace with an empty name. The director is added to the list of objects in the workspace. Increment the version number of the workspace.

Parameters:
workspace - The workspace of this object.

CSPDirector

public CSPDirector(CompositeEntity container,
                   java.lang.String name)
            throws IllegalActionException,
                   NameDuplicationException
Construct a director in the given container with the given name. If the container argument must not be null, or a NullPointerException will be thrown. If the name argument is null, then the name is set to the empty string. Increment the version number of the workspace.

Parameters:
container - Container of the director.
name - Name of this director.
Throws:
IllegalActionException - If the director is not compatible with the specified container.
NameDuplicationException - If the container not a CompositeActor and the name collides with an entity in the container.
Method Detail

clone

public java.lang.Object clone(Workspace workspace)
                       throws java.lang.CloneNotSupportedException
Clone the director into the specified workspace. The new object is not added to the directory of that workspace (you must do this yourself if you want it there). The result is a new director with no container, no pending changes to the topology, current time is 0.0, and no actors are delayed or blocked.

Overrides:
clone in class CompositeProcessDirector
Parameters:
workspace - The workspace for the cloned object.
Returns:
The new CSPDirector.
Throws:
java.lang.CloneNotSupportedException - If one of the attributes cannot be cloned.
See Also:
NamedObj.exportMoML(Writer, int, String), NamedObj.setDeferringChangeRequests(boolean)

delayDependency

public Dependency delayDependency(double delay)
Return a boolean dependency representing a model-time delay of the specified amount.

Specified by:
delayDependency in interface TimedDirector
Parameters:
delay - A non-negative delay.
Returns:
A boolean dependency representing a delay.

initialize

public void initialize()
                throws IllegalActionException
Reset flags to initialize values.

Specified by:
initialize in interface Initializable
Overrides:
initialize in class CompositeProcessDirector
Throws:
IllegalActionException - If the super class throws it.

newReceiver

public Receiver newReceiver()
Return a new CSPReceiver compatible with this director. In the CSP domain, we use CSPReceivers.

Overrides:
newReceiver in class CompositeProcessDirector
Returns:
A new CSPReceiver.

postfire

public boolean postfire()
Return false if deadlock has occurred and there are no input ports, or if stop() has been called, and true otherwise.

Specified by:
postfire in interface Executable
Overrides:
postfire in class ProcessDirector
Returns:
False if no more execution is possible, and true otherwise.

suggestedModalModelDirectors

public java.lang.String[] suggestedModalModelDirectors()
Return an array of suggested directors to be used with ModalModel. This is the FSMDirector followed by the NonStrictFSMDirector.

Overrides:
suggestedModalModelDirectors in class Director
Returns:
An array of suggested directors to be used with ModalModel.
See Also:
Director.suggestedModalModelDirectors()

wrapup

public void wrapup()
            throws IllegalActionException
Override the base class to stop any actors that might be stalled in a call to delay().

Specified by:
wrapup in interface Initializable
Overrides:
wrapup in class CompositeProcessDirector
Throws:
IllegalActionException - If the parent class throws it.

_actorDelayed

protected void _actorDelayed(double delta,
                             CSPActor actor)
                      throws InvalidStateException
Called by a CSPActor when it wants to delay. When the director has advanced time to "getCurrentTime() + delta", the process corresponding to the actor will continue. Note that actors can only deal with delta time.

The method waitForDeadlock() in CSPActor calls this method with a zero argument. Thus the process will continue the next occasion time deadlock occurs.

Parameters:
delta - The length of time to delay the actor.
actor - The actor being delayed.
Throws:
InvalidStateException - If an actor is delayed for negative time.

_areThreadsDeadlocked

protected boolean _areThreadsDeadlocked()
Returns true if all active processes are either blocked or delayed, false otherwise.

Overrides:
_areThreadsDeadlocked in class CompositeProcessDirector
Returns:
false If the number of blocked processes is less than the number of active actors; return true otherwise.

_areAllThreadsStopped

protected boolean _areAllThreadsStopped()
Return true if the count of active processes equals the number of stopped, blocked, and delayed threads. Otherwise return false.

Overrides:
_areAllThreadsStopped in class ProcessDirector
Returns:
True if all threads are stopped.

_receiverStatus

private java.lang.String _receiverStatus()
                                  throws InvalidStateException,
                                         IllegalActionException
Return a string describing the status of each receiver.

Returns:
A string describing the status of each receiver.
Throws:
IllegalActionException
InvalidStateException

_receiverStatus

protected static java.lang.String _receiverStatus(Receiver receiver)
Return a string describing the status of the specified receiver.

Parameters:
receiver - The receiver to describe.
Returns:
A string describing the status of the specified receiver.

_resolveInternalDeadlock

protected boolean _resolveInternalDeadlock()
                                    throws IllegalActionException
Respond to a deadlock. This is where nearly all the control for the model at this level in the hierarchy is located.

Deadlock occurs if the number of blocked and delayed processes equals the number of active processes. The method looks for three cases in the following order: are there topology changes waiting to happen, are there any processes delayed, are all the processes blocked trying to rendezvous.

If there are changes to the topology waiting to happen, they are performed and the execution of the model continues. Note that the result of performing the topology changes may be to remove the deadlock that had occurred.

If the number of delayed processes is greater than zero, then time deadlock has occurred. If one or more processes are delayed waiting for deadlock to occur, then those processes are resumed and time is not advanced. Otherwise time is advanced and the earliest delayed process is resumed.

If all the processes are blocked, then real deadlock has occurred, and this method returns false. If there are no levels above this one in the hierarchy, then real deadlock marks the end of executing the model.

Overrides:
_resolveInternalDeadlock in class CompositeProcessDirector
Returns:
False if real deadlock occurred, true otherwise.
Throws:
IllegalActionException - If setting the model time, or getting a parameter throws it.

_getNextTime

private Time _getNextTime()
Get the earliest time which an actor has been delayed to. This should always be the top link on the list.


_registerDelayedActor

private void _registerDelayedActor(Time actorTime,
                                   CSPActor actor)
Keep track of when and for how long processes are delayed.

Parameters:
actor - The delayed actor.
actorTime - The time at which to resume the actor.