필터 지우기
필터 지우기

Updating a parallel.pool.Constant within a parfor loop

조회 수: 5 (최근 30일)
Audrey Blizard
Audrey Blizard 2024년 4월 8일
답변: Edric Ellis 2024년 4월 17일
Background: I am using Casadi to create a function object that is then used in my parfor loop to be sovled over 95 parameters, and over 1000 timesteps. From my understanding, using a parallel pool constant would reduce the communciation overhead as it allows the function to only be distributed to the workers for the first timestep rather every time. Here is a simplified version of the code, where fnc is the casadi function.
for i =1:1000
parfor j = 1:95
rslt(j,1) = fnc.call(params) % params is created in the parallel loop
vld(j,1) = fnc.stats.success
end
end
Question: How do the workers handle changes to the parallel.pool.Constant value within the parfor calculation. For example, the way Casadi indicates if the solve is successful is update the value fnc.stats.success after the function is called. Would it work to simply update fnc to a parallel.pool.constant and switch fnc to fnc.Value in the loop? or will this not work since the value is changing within the parallel calculation?
  댓글 수: 2
Matt J
Matt J 2024년 4월 8일
Did you try it?
Audrey Blizard
Audrey Blizard 2024년 4월 8일
I did, but I can't really tell if it working. Because my code is only unsuccessful a very few number of times, and not consistently, I cant tell if I just get all valid because the code is working or because the variable is not updating correctly.

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

채택된 답변

Edric Ellis
Edric Ellis 2024년 4월 17일
You can't directly update the Value of a parallel.pool.Constant inside a parfor loop - not least because the parfor constraints disallow it. For example, this doesn't work:
c = parallel.pool.Constant(magic(4));
parfor i = 1:3
c.Value = 1 + c.Value; % doesn't work
end
Error: Unable to classify the variable 'c' in the body of the parfor-loop. For more information, see Parallel for Loops in MATLAB, "Solve Variable Classification Issues in parfor-Loops".
If you put some sort of handle Class instance inside your parallel.pool.Constant, you can modify it, and the modifications will persist. However, I would caution against this approach because then you might get some slightly odd behaviour since each worker will retain a "memory" of those modifications. Here's a simple example using containers.Map , which is a handle class:
c = parallel.pool.Constant(containers.Map());
for i = 1:3
parfor j = 1:4
map = c.Value;
key = string(i) + "-" + string(j);
map(key) = [i,j];
disp(keys(map));
end
end
Note that each worker builds up a memory of each iteration.

추가 답변 (0개)

카테고리

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

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by