matlabfor-loopbroadcastflagsspmd

How to use a flag variable to break all the for-loops in spmd statement?


I want to run multiple for-loops in Matlab, each for-loop have large number of iterations so I use spmd to run them in parallel. All the for-loops will be break out if in a for-loop, a criterion is met. How do I do this? Here is the simplified version of my program:

    spmd
        flag = false;
        for i = 1:1:inf
            if flag == true
                break;
            end
            fprintf("x = %d, i = %d\n", labindex, i);
            if labindex == 7 && i == 111  %some condition is met
                flag = true;
            end
            flag = labBroadcast(?, flag); %I don't know how to broadcast flag to other workers
        end
    end

Solution

  • Instead of labBroadcast, what you need to use here is gop. (In newer versions, this has been renamed to spmdReduce. This will let you combine together all the local values of flag from each worker to see if any worker has set flag to true, like this:

    spmd
        for i = 1:inf
            flag = computeLocalFlag();
            % Combine all local values of flag using the "or" function
            % to see if any value is true:
            globalFlag = spmdReduce(@or, flag);
            if globalFlag
                break; % This is fine, because you're not trying to break out of spmd
            end
        end
    end