MATLAB: Parallel pool costant doesn’t work as expected

parallel computingParallel Computing Toolboxparfor

I got an error using parallel.pool.Constant. In the script i create a struct with parallel.pool.Constant value as follow:
globalVar = who('global');
for index = 1:size(globalVar,1)
constant.(globalVar{index}) = parallel.pool.Constant(eval(globalVar{index}));
end
The struct was created correclty but into parfor-loop, when i call function that use this variable i can't access to constant struct. The code is the follow:
mainScript.m
parfor i = 1:tot
result = myFunction();
end
myFunction.m()
% some code here

var = otherFunction();
otherFunction.m
if ~isempty(getCurrentWorker)
global numberOfWorkers;
global numberOfTasks;
else
numberOfWorkers = constant.numberOfWorkers.Value;
numberOfTasks = constant.numberOfTasks.Value;
end
% some code here
The error that I receive is the follow:
Undefined variable "constant" or class "constant.numberOfWorkers.Value".
An UndefinedFunction error was thrown on the workers for 'costant'. This may be because the file containing
'costant' is not accessible on the workers. Specify the required files for this parallel pool using the command:
addAttachedFiles(pool, ...). See the documentation for parpool for more details.
Undefined function or variable 'costant'.

Best Answer

You need to pass the Constant instances explicitly to the functions invoked on the workers, rather than using global. As usual, Parallel Computing Toolbox does not synchronise global variables between the client and the workers. So, you need to do something more like this:
mainScript.m
parfor i = 1:tot
result = myFunction(constant);
end
myFunction.m
function myFunction(constant)
% some code here

var = otherFunction(constant);
otherFunction.m
function otherFunction(constant)
numberOfWorkers = constant.numberOfWorkers.Value;
numberOfTasks = constant.numberOfTasks.Value;
% some code here