Main Content

Specify Maximum Number of Threads in parfor-Loops

This example shows how to specify the maximum number of threads to use for a parfor-loop. Because you specify the maximum number of threads to use, the generated MEX function executes the loop iterations in parallel on as many cores as available, up to the maximum number that you specify. If you specify more threads than there are cores available, the MEX function uses the available cores.

  1. Write a MATLAB® function, specify_num_threads, that uses one input to specify the maximum number of threads to execute a parfor-loop in the generated MEX function. For example:

    function y = specify_num_threads(u) %#codegen
      y = ones(1,100);
      % u specifies maximum number of threads
      parfor (i = 1:100,u)
        y(i) = i;
      end
    end
    

  2. Generate a MEX function for specify_num_threads. Use -args {0} to specify that input u is a scalar double. Use -report to generate a code generation report. At the MATLAB command line, enter:

    codegen -report specify_num_threads -args {0}
    codegen generates a MEX function, specify_num_threads_mex, in the current folder.

  3. Run the MEX function, specifying that it try to run in parallel on four threads. At the MATLAB command line, enter:

    specify_num_threads_mex(4)

    The generated MEX function runs on up to four cores. If less than four cores are available, the MEX function runs on the maximum number of cores available at the time of the call.