Parallel pool costant doesn't work as expected

7 views (last 30 days)
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'.

Accepted Answer

Edric Ellis
Edric Ellis on 1 Jun 2018
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

More Answers (0)

Categories

Find more on Parallel for-Loops (parfor) in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!