Parallel pool costant doesn't work as expected

8 次查看(过去 30 天)
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'.

采纳的回答

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

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Parallel for-Loops (parfor) 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by