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

조회 수: 1 (최근 30일)
Ryan
Ryan 2022년 12월 22일
답변: Kunal Kandhari 2023년 1월 18일
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