Main Content

spmdIndex

Index of current worker in spmd block

Since R2022b

    Description

    id = spmdIndex returns the index of the worker currently executing the function in an spmd block or a communicating job. When workers run an spmd block or a communicating job begins execution, a unique index is assigned to each worker.

    The value of spmdIndex is an integer between 1 and the number of workers running in the current spmd block or communicating job. To get the number of workers running the current spmd block, use the spmdSize function.

    A worker gets the same value id inside every spmd block for the duration of a parallel pool.

    example

    Examples

    collapse all

    View the indices of workers in an spmd block.

    p = parpool('Threads',2);
    spmd
        spmdIndex
    end
    
    Worker 1: 
             1
      
    Worker 2: 
            2

    View the indices of workers in a parpool loop run in the same two worker pool, p.

    parfor a=1:4
        [a,spmdIndex]
    end
    ans =
         3     1
    ans =
         2     1
    ans =
         1     1
    ans =
         4     1
    

    Output Arguments

    collapse all

    Index of current worker, specified as a positive integer. The value of this input must be less than or equal to the output of the spmdSize function in the current spmd block or communicating job.

    Tips

    In an spmd block, because you have access to all workers individually and control what the workers execute, each worker has a unique index.

    However, inside a parfor-loop, spmdIndex always returns a value of 1 on all workers in all iterations.

    Extended Capabilities

    Version History

    Introduced in R2022b