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

3 次查看(过去 30 天)
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 个)

Kunal Kandhari
Kunal Kandhari 2023-1-18
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:

类别

Help CenterFile Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息

产品


版本

R2022b

Community Treasure Hunt

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

Start Hunting!

Translated by