我不parfor
经常使用,但以下方法(改编自此处)似乎有效:
parpool('local',4); % create parallel pool of workers
spmd
rng(123); % set the same seed in each worker
end
parfor k = 1:12
r = rand; % generate a random number
w = getCurrentWorker;
fprintf('Worker %i, iteration %i, random number %f\n', w.ProcessId, k, r)
end
请注意每个工人如何以相同的顺序生成相同的随机数。(迭代随机分配给工人,并以随机顺序运行;这是设计使然)。
Starting parallel pool (parpool) using the 'local' profile ...
connected to 4 workers.
Worker 11688, iteration 1, random number 0.275141
Worker 17188, iteration 2, random number 0.275141
Worker 18408, iteration 4, random number 0.275141
Worker 18408, iteration 3, random number 0.423046
Worker 5812, iteration 6, random number 0.275141
Worker 5812, iteration 5, random number 0.423046
Worker 11688, iteration 8, random number 0.423046
Worker 11688, iteration 7, random number 0.973406
Worker 17188, iteration 9, random number 0.423046
Worker 18408, iteration 10, random number 0.973406
Worker 5812, iteration 11, random number 0.973406
Worker 17188, iteration 12, random number 0.973406