Parallel Region model element
PJRegion defines a piece of code that can be run in parallel to the EJS model
Usage
To add a set of parallel code to your model, drag the icon element to the list of your model elements
and enter the code for each of the parts of your parallel code.
The editor provides a page for each of the following parts:
- Variables: Defines optional variables for the code. The EJS model cannot access these variables, hence there is no synchronization (with the EJS model) needed.
- Preliminary: Defines optional initialization code for this element. This code is run sequentially with the EJS model, hence there are no synchronization problems.
- Parallel: Defines the code that wil run in parallel with the EJS model. Beware of potential synchronization problems. It is recommended that only local variables
(defined in the Variables editor) are used for writing purposes.
- Final: Defines optional final code for this element. This code will be run when the Parallel code is done and will run sequentially with the EJS model
(i.e. when the model is idle). No synchronization problems are expected.
The code in the Parallel editor can make use of the following predefined constants and methods:
- int _threadCount: the number of threads running
- int _threadIndex: the index of the current thread
- int _firstThreadIndex(int min, int max): divides the range into several subintervals and returns the first index for the current thread
- int _lastThreadIndex(int min, int max): divides the range into several subintervals and returns the first index for the current thread
The element implements the following basic methods:
- long startAndWait(int nThreads): runs the code in nThreads parallel threads and waits for completion. Returns the time elapsed in milliseconds.
- boolean startAndReturn(int nThreads): executes the code in parallel with nThreads starting in a separate Thread. (That it, the call returns immediately.) Returns true is successfully started.
- int getThreadCount(): returns the number of threads actually used in the last execution.
- long getExecutionTime(): returns the time (in milliseconds) of the last execution. -1 if the region has never been run.
- void resetInitialTime(): resets the initial time to measure the execution time. (The initial time is reset automatically when the startAndReturn method is called.)
- boolean isAlive(): whether the code is currently running.
- void release(): releases the thread created for the element.(The element is released automatically when the simulation quits.)
Example of use
pjRegion.startAndWait(4); // runs the parallel code using four threads
pjRegion.startAndReturn(0); // runs the parallel code in a separate thread using as any processors as available
_println ("The parallel code executed last time using "+pjRegion.getThreadCount()+" threads,");
_println ("and took "+pjRegion.getExecutionTime()+" milliseconds.");