parfor
Parallelfor
-loop
Syntax
parfor LoopVar = InitVal:EndVal; Statements; end
parfor (LoopVar = InitVal:EndVal, NumThreads); Statements; end
Description
parfor
creates a loop in a generated MEX function or in C/C++ code that runs in parallel on shared-memory multicore platforms.LoopVar
=InitVal
:EndVal
;Statements
; end
Theparfor
-loop executes theStatements
for values ofLoopVar
betweenInitVal
andEndval
.LoopVar
specifies a vector of integer values increasing by 1.
parfor (
uses a maximum ofLoopVar
=InitVal
:EndVal
,NumThreads
);Statements
; endNumThreads
threads when creating a parallelfor
-loop.
Examples
Input Arguments
Limitations
You must use a compiler that supports the Open Multiprocessing (OpenMP) application interface. SeeSupported Compilers. If you use a compiler that does not support OpenMP,MATLAB Codertreats the
parfor
-loops asfor
循环。在生成的墨西哥人函数或C / c++鳕鱼e, the loop iterations run on a single thread.The OpenMP application interface is not compatible with JIT MEX compilation. SeeJIT Compilation Does Not Support OpenMP.
Do not use the following constructs inside
parfor
-loops:You cannot call extrinsic functions using
coder.extrinsic
in the body of aparfor
-loop.You cannot write to a global variable inside a
parfor
-loop.MATLAB Coderdoes not support the use of
coder.ceval
in reductions. For example, you cannot generate code for the followingparfor
-loop:parfori = 1:4 y = coder.ceval(“myCFcn”,y,i);end
coder.ceval
and call this function in theparfor
-loop. For example:parfori = 1:4 y = callMyCFcn(y,i);endfunctiony = callMyCFcn(y,i) y = coder.ceval('mCyFcn',y , i);end
The type of the loop index must be representable by an integer type on the target hardware. Use a type that does not require a multiword type in the generated code.
parfor
for standalone code generation requires the toolchain approach for building executables or libraries. Do not change settings that cause the code generator to use the template makefile approach. SeeProject or Configuration is Using the Template Makefile.
For a comprehensive list of restrictions, seeparfor Restrictions.
Tips
Use a
parfor
-loop when:You need many loop iterations of a simple calculation.
parfor
divides the loop iterations into groups so that each thread can execute one group of iterations.You have loop iterations that take a long time to execute.
Do not use a
parfor
-loop when an iteration in your loop depends on the results of other iterations.Reductions are one exception to this rule. Areduction variableaccumulates a value that depends on all the iterations together, but is independent of the iteration order.