MATLAB Language Executing commands in parallel using a "Single Program, Multiple Data" (SPMD) statement


Example

Unlike a parallel for-loop (parfor), which takes the iterations of a loop and distributes them among multiple threads, a single program, multiple data (spmd) statement takes a series of commands and distributes them to all the threads, so that each thread performs the command and stores the results. Consider this:

poolobj = parpool(2);    % open a parallel pool with two workers

spmd
    q = rand(3);         % each thread generates a unique 3x3 array of random numbers
end

q{1}             % q is called like a cell vector
q{2}             % the values stored in each thread may be accessed by their index

delete(poolobj)  % if the pool is closed, then the data in q will no longer be accessible

It is important to note that each thread may be accessed during the spmd block by its thread index (also called lab index, or labindex):

poolobj = parpool(2);        % open a parallel pool with two workers

spmd
    q = rand(labindex + 1);  % each thread generates a unique array of random numbers
end

size(q{1})                   % the size of q{1} is 2x2
size(q{2})                   % the size of q{2} is 3x3

delete(poolobj)              % q is no longer accessible

In both examples, q is a composite object, which may be initialized with the command q = Composite(). It is important to note that composite objects are only accessible while the pool is running.