accessing global vars in functions in parfor loops

1 view (last 30 days)
Hi, I am trying to use global variables to control function behavior to see which option works best (so using globals is only a temporary solution and the global vars will not be changed during run-time)
here's the code:
function parfor_globals
global TESTVAR_A
TESTVAR_A = 3;
parfor i = 1:2
disp(TESTVAR_A)
parfor_globals__sub();
end
end
function parfor_globals__sub()
global TESTVAR_A;
if isempty(TESTVAR_A)
disp('empty')
else
disp('not empty')
end
end
the problem is that in parfor_globals__sub() the 'TESTVAR_A' does not contain the value set at the beginning of the code, as you can see from the output:
>> parfor_globals
3
empty
3
empty
I am aware that within parfor-loops, global vars cannot be changed across workers. This is not an issue for me as I do not intend to change the value during runtime.
Is there any solution available for me?
-- Jakob (tested with R2016b and R2018b)
  2 Comments
Adam
Adam on 9 Oct 2018
I'd be surprised if global variables worked at all in parfor loops, to be honest! They would cause no end of potential chaos. The fact that you only use them in a certain way doesn't really matter because they have the capability to be misused across workers and the main thread, which I would have thought would simply make them unusable in parallel code.
I would not think you would ever want to either, even if it were possible because the potential for bugs would be way higher than just passing data explicitly.
thengineer
thengineer on 9 Oct 2018
I know I'm probably asking too much here. Guess I'll have to do this without parfor then. Actually I was hoping for some special construct like 'parallel.pool.Constant' that would make the data just available, but well...

Sign in to comment.

Answers (1)

Steven Lord
Steven Lord on 9 Oct 2018
See Edric's answer to this question.

Categories

Find more on MATLAB Parallel Server in Help Center and File Exchange

Products


Release

R2016b

Community Treasure Hunt

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

Start Hunting!