使用單程式多資料(SPMD)語句並行執行命令

與並行 for 迴圈(parfor)不同,它採用迴圈的迭代並在多個執行緒之間分配它們,單個程式,多個資料(spmd)語句接受一系列命令並將它們分配給所有執行緒,因此每個 thread 執行命令並儲存結果。考慮一下:

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

重要的是要注意,每個執行緒可以在 spmd 塊中通過其執行緒索引(也稱為實驗室索引或 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

在這兩個示例中,q 是一個複合物件 ,可以使用命令 q = Composite() 進行初始化。請務必注意,只有在池執行時才能訪問複合物件。