How to run two loops simulatenously which share varaibles in MATLAB?

77 Views Asked by At

I am trying to implement some logic which can be simplified in the example below:

count = 5;
value = 0;
parfor i = 1:2
    if i == 1
        for u = 0:count
            %Do dome work
            pause(5);
            value = value + 1;
        end
    else
        while true
           disp(value)
        end
    end
end

I wanted to run two loops in parallel which share a certain variable(s). Above is the closest I could get. I realized if I used the parfor as shown, I can call each on its own worker. Unfortunately, I am getting the error The PARFOR loop cannot run due to the way variable 'value' has been used

Anyone with an idea how I can achieve the above successfully?

1

There are 1 best solutions below

3
On

It's hard to tell what you actually want to do here, but parfor does not look like a good fit. You might be better off using spmd, which is designed to allow worker-to-worker communication. However, note that the communication methods used inside spmd are essentially "two-sided" - i.e. both sender and receiver must be involved. Something like this:

spmd
    if labindex == 1
        for u = 0:count
            %Do dome work
            pause(5);
            value = value + 1;
            labSend(value, 2); % send value to other worker
        end
        labSend([], 2) % tell it to finish
    elseif labindex == 2
        value = labReceive(1);
        while ~isempty(value)
            % do stuff

            % get updated "value"
            value = labReceive(1);
        end
    end
end