Main Content

Ensure Thatparfor- 环路是独立的

If you get an error when you convertfor-loops toparfor-loops, ensure that yourparfor-loop iterations are independent.parfor-loop iterations haveno guaranteed order, while the iteration order infor-loops issequential. Alsoparfor-loop iterations are performed on different MATLAB®workers in the parallel pool, so that there is no sharing of information between iterations. Therefore oneparfor-loop iteration must not depend on the result of a previous iteration. The only exception to this rule is to accumulate values in a loop using还原变量.

The following example produces equivalent results, using afor-loop on the left and aparfor-loop on the right. Try the example in your MATLAB Command Window:

清除Afori = 1:8 A(i) = i;endA
A = 1 2 3 4 5 6 7 8
清除Aparfori = 1:8 A(i) = i;endA
A = 1 2 3 4 5 6 7 8

Each element ofAis equal to its index. Theparfor- 环的起作用是因为每个元素仅由索引环变量确定,并且不取决于其他变量。for-loops with independent tasks are ideal candidates forparfor-loops.

Note

By default,parforautomatically starts a parallel pool of workers, if you have not started one already.parforcreates a pool using your default cluster profile, if you have set your parallel preferences accordingly.

In the example, the array elements are available in the client workspace after theparfor-loop, exactly as with afor-loop.

Now use a nonindexed variable inside the loop, or a variable whose indexing does not depend on the loop variablei. Try these examples, and note the values ofdi之后:

清除Ad = 0; i = 0;fori = 1:4 d = i*2; A(i) = d;endA d i
A = 2 4 6 8 d = 8 i = 4
清除Ad = 0; i = 0;parfori = 1:4 d = i*2; A(i) = d;endA d i
A = 2 4 6 8 d = 0 i = 0

Although the elements ofAare the same in both examples, the value ofdis not. In thefor-loop, the iterations are executed sequentially, so afterwarddhas the value it held in the last iteration of the loop. In theparfor-loop, however, the iterations execute in parallel, so it is impossible to assignd循环末端的定义值。这种情况也适用于循环变量i. Therefore,parfor循环行为定义,以便它不affect the valuesdioutside the loop. Their values remain the same before and after the loop. If the variables in yourparfor-loop are not independent, then you might get different answers from those in thefor-loop. In summary, aparfor-loop requires that each iteration be independent of the other iterations. All code that follows theparforstatement should not depend on the loop iteration sequence.

Code Analyzer can help diagnose whether the loop iterations are dependent. The code in the example shows iterations defined in terms of the previous iteration:

parfork = 2:10 x(k) = x(k-1) + k;end
Look for Code Analyzer messages in the MATLAB Editor. In this case, Code Analyzer reports the dependency problem.

In other cases, however, Code Analyzer is unable to mark dependencies.

For help with other commonparforproblems, seeNested parfor and for-Loops and Other parfor Requirements.

See Also

Related Examples

More About