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 Center および File ExchangeParallel 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