question regarding what is allowed in a parfor loop

4 visualizaciones (últimos 30 días)
sasha
sasha el 8 de Ag. de 2014
Respondida: Jill Reese el 8 de Ag. de 2014
I am confused about a section of the description of how to use parfor:
" Next assume that A, B, and C are variables and that f, g, and h are functions:
parfor i = 1:n
t = f(A(i));
u = g(B(i));
C(i) = h(t, u);
end
If the time to compute f, g, and h is large, parfor will be significantly faster than the corresponding for statement, even if n is relatively small. Although the form of this statement is similar to a for statement, the behavior can be significantly different. Notably, the assignments to the variables i, t, and u do not affect variables with the same name in the context of the parfor statement. The rationale is that the body of the parfor is executed in parallel for all values of i, and there is no deterministic way to say what the "final" values of these variables are. Thus, parfor is defined to leave these variables unaffected in the context of the parfor statement. By contrast, the variable C has a different element set for each value of i, and these assignments do affect the variable C in the context of the parfor statement. "
This is a bit of a long paragraph, but I'm mostly confused about the last line about it affecting C. How is this any different than saying:
parfor i = 1:n
C(i) = h(f(A(i)), g(B(i)));
end
I think in this second case, that there should be no difference between using a parfor loop and just a for loop. I don't really understand why this is not the case in the first example

Respuesta aceptada

Jill Reese
Jill Reese el 8 de Ag. de 2014
This documentation is trying to explain when local variables defined in a parfor loop body are available for use outside the parfor loop body (i.e. variable lifetimes or variable scoping).
Here is a simplified example:
t = -1;
for i = 1:7
t = i;
C(i) = i;
end
C % [same as 1:7]
t % This has the value 7 from the last iteration of the for loop
t = -1;
parfor i = 1:7
t = i;
C(i) = i;
end
C % [same as 1:7]
t % This has the value -1 because its context is different from the variable t inside the loop
Because parfor iterations can be performed in any order, the value from the "last" iteration is no longer a well-defined, deterministic quantity. For this reason, local variables within the parfor loop body can only impact the workspace outside the parfor loop body if they were indexed with the loop variable (like C in the above examples). The final quantity C is deterministic although the order in which its entries are filled in is not deterministic.

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by