Constructing class objects before the parfor loop

조회 수: 2 (최근 30일)
Nagat Elrefaei
Nagat Elrefaei 2022년 8월 2일
댓글: Nagat Elrefaei 2022년 8월 2일
Hi!
I am using OOP by constructing objects and running it multiple times within a while loop. In order to make the code faster, I pass my initial arguments to the class before the loop so it does not need to be initilized everytime.
I am tried switching the while loop to a parfor loop since I have multiple objects which I need to run independently every iteration. However, I am not able to initialize the objects before the parfor loop nor can I figure out how to call the objects after the loop since they are defined within the loop.
I am very new to oop so I might be wrong on many things and I would really appreciate the help.
Thanks!

채택된 답변

Walter Roberson
Walter Roberson 2022년 8월 2일
편집: Walter Roberson 2022년 8월 2일
It is valid to construct objects and use them in parfor loops.
However, the mechanism used is that the objects are effectively save() on the client and load() on the worker. This will fail if the objects contain anything that is not serializable such as a Java object or an identifier to an open file, or if you are using handle objects and you expect the workers to all be referencing the same object instead of copies of the object.
Global variables and persistent variables are also not copied.
  댓글 수: 3
Walter Roberson
Walter Roberson 2022년 8월 2일
You are updating a variable within a loop. The A for the second time step is not independent from the A for the first time step: the second time step depends on the first having already been run.
However when you convert to a parfor, something like
for K = 1 : ceil(stoptime/timestep) + 1
t = (K-1) * timestep;
A = A.Runtimestep(t);
end
Then you run into the problem that the time steps are done out of order, typically starting at the end, and not in a fixed order. If you could update A in such a case you would be updating out of order. The 20th might get run then the 16th then the 5th then the 19th, and so on. And the updates for one worker could not affect other workers.
There are a small number of cases in which parfor permits variables to be updated. The permitted cases involve "reduction variables" such as F = F + calculation, or F = F * calculation — cases in which algebraically you can do the updates out of order as long as they all get done.
You will not be able to update your objects for use in later iterations; even if the updates turn out to equivalent to reduction variables, MATLAB is not able to analyze methods of classes to prove that updating out of order is safe.
Nagat Elrefaei
Nagat Elrefaei 2022년 8월 2일
Thank you very much! I really appreciate the help and detailed explaination.

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Parallel for-Loops (parfor)에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by