필터 지우기
필터 지우기

Is this combination of parfor and global variables prone to errors?

조회 수: 5 (최근 30일)
Mitsu
Mitsu 2021년 10월 26일
댓글: Mitsu 2021년 10월 26일
In the main script mainScript.m, a parfor loop goes through N cases.
In each case of the parfor loop, the function principalFunction() is called.
%mainScript.m
parfor i = 1:N
someInputData = inputData(i,:);
results(i,1) = principalFunction(someInputData);
end
No global variables are declared or used anywhere in this file.
However, principalFunction() is a function that will declare global variables, and share them across function1, ..., functionN that will be called within principalFunction(). These functions will use the global variables along with any local variables passed.
%principalFunction.m
function result = principalFunction(someInputData)
global globalVariable1 globalVariable 2
% Call some functions where local variables are passed, and which will use
% global variables as well
localVariable1 = function1(someInputData);
localVariable2 = function2(someInputData,localVariable1);
localVariable3 = function3(someInputData);
result = functionN(localVariable1,localVariable2,localVariable3);
end
Most functions are part of a third-party library, and rewritting them to avoid using global variables is not an option.
I have tried a number of cases in parallel and in series for N < 30, and it seems to yield the same results.
However, I would still like to know for sure that there is nothing I am overlooking in this approach. Is there?

채택된 답변

Walter Roberson
Walter Roberson 2021년 10월 26일
That should work, as long as the principal function sets the global variables on every call, or at least tests whether they already exist non-empty and if not then assigns to them.
  댓글 수: 1
Mitsu
Mitsu 2021년 10월 26일
Yes, they are initialized in the principal function before they are used anywhere else. Thank you.

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

추가 답변 (0개)

카테고리

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

제품


릴리스

R2019a

Community Treasure Hunt

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

Start Hunting!

Translated by