使用单程序多数据(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()
进行初始化。请务必注意,只有在池运行时才能访问复合对象。