Ensure Transparency in parfor-Loops or spmd Statements - MATLAB & Simulink (original) (raw)

Main Content

The body of a parfor-loop or spmd block must be transparent. Transparency means that all references to variables must be visible in the text of the code.

In the following examples, the variable X is not transferred to the workers. Only the character vector 'X' is passed toeval, and X is not visible as an input variable in the loop or block body. As a result, MATLABĀ® issues an error at run time.

X = 5; parfor ii = 1:4 eval('X'); end X = 5; spmd eval('X'); end

Similarly, you cannot clear variables from a workspace by executing clear inside a parfor or spmd statement:

parfor ii = 1:4 <statements...> clear('X') % cannot clear: transparency violation <statements...> end spmd; clear('X'); end

Alternatively, you can free up memory used by a variable by setting its value to empty when it is no longer needed.

parfor ii = 1:4 <statements...> X = []; <statements...> end

In the case of spmd blocks, you can clear its Composite from the client workspace.

In general, the requirement for transparency restricts all dynamic access to variables, because the entire variable might not be present in any given worker. In a transparent workspace, you cannot create, delete, modify, access, or query variables if you do not explicitly specify these variables in the code.

Examples of other actions or functions that violate transparency in aparfor-loop include:

Note

Transparency applies only to the direct body of the parfor orspmd construct, and not to any functions called from there. One workaround for save and load is to hide the calls to save and load inside a function. An alternative workaround is to call save with the"-fromstruct" option. For more information, see Save Variables in parfor-Loops.

MATLAB_does_ successfully execute eval and evalc statements that appear in functions called from the parfor body.

You can run SimulinkĀ® models in parallel with the parsim command instead of using parfor-loops. For more information and examples of using Simulink in parallel, see Running Multiple Simulations (Simulink).

See Also

parfor | spmd