Calling nested functions inside a parfor loop

조회 수: 13 (최근 30일)
Antoine GUELLIER
Antoine GUELLIER 2015년 3월 14일
댓글: Hung Dao 2021년 7월 6일
Hello,
I am trying to parallelize a program. I am experiencing issues with a parallel for and nested functions. My main function contains a big parfor loop, and several nested functions. These nested function access (both read and write) the variables declared in the main function. Without parallelism, everything works fine: my nested function do their job and update the variables in my main function (as it is supposed to be). This is true whether I call the nested function directly or using a handle. However, when I switch to a parfor (and thus use handles, as it should be), and make so that no error appear, the nested function no longer updates the variables from the main function. Said otherwise, MATLAB does not detect any error, but my program doesn't really do anything!
Below is a representative example:
function garbage
accumulator = [];
handleFoo = @foo;
for i=1:10
aux = i*5;
handleFoo(aux);
end
accumulator
function foo(n)
accumulator(end+1) = n;
end
end
Running this program as-is will result "accumulator" equal to 1:10. But simply changing the for loop to a parfor will resut in an empty array.
Is this the expected behavior of MATLAB? Is there away to work around this? I could not find help on this specific question anywhere.
Thank you Antoine

채택된 답변

Edric Ellis
Edric Ellis 2015년 3월 16일
Yes, this is expected behaviour - the MATLAB workers operating on the body of your parfor loop are separate MATLAB processes, and they do not share thing like handle variables, or nested function workspaces. All data that flows into and out from a parfor loop must go through explicit variable transfers.
  댓글 수: 2
Antoine GUELLIER
Antoine GUELLIER 2015년 3월 16일
편집: Antoine GUELLIER 2015년 3월 16일
Thank you! I supposed it was this way, but I didn't see this fact explicited anywhere.
Hung Dao
Hung Dao 2021년 7월 6일
Is there a solution for this? I am having a similar issue. I want to call a function f inside a parfor loop. I am using feval(f, arguments of f). The function f calls another functions. Without parfor, it works OK but with parfor it results in an error.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Loops and Conditional Statements에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by