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

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)
if(value > count)
break
end
end
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개)

Hi,
Not all MATLAB for loops can be converted to parfor.
In your this part of code:
disp(value)
if(value > count)
break
end
there is an dependency of variable value on the following piece of code:
value = value + 1;
This stops you from being able to use a parfor.
To solve these problems, you must modify the code to use parfor. The body of the parfor-loop is executed in a parallel pool using multiple MATLAB workers in a nondeterministic order. Therefore, you have to meet following requirements for the body of the parfor-loop:
  • The body of the parfor-loop must be independent. One loop iteration cannot depend on a previous iteration, because the iterations are executed in parallel in a nondeterministic order.
You can read more sbout the same using the following resources:

카테고리

도움말 센터File Exchange에서 Execution Speed에 대해 자세히 알아보기

제품

릴리스

R2022b

질문:

2022년 12월 22일

답변:

2023년 1월 18일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by