Global and Perfumery

Inside the parfor loop parfor I'm trying to call a function that accesses global no avail.

Function

 function a = getA() global OPTIONS; a=OPTIONS.PROBLEM.A; end 

The loop:

 parfor i=1:3 b=getA(); end 

Error:

 Error using parallel_function (line 589) Attempt to reference field of non-structure array. 

What am I doing wrong?

+6
source share
2 answers

From the parfor documentation :

The body of a parfor-loop element cannot contain global or constant variable declarations.

In the context of your problem, that is, calling a function in parfor , which, in turn, refers to global , it means: " parfor probably will not give the expected or meaningful results."

It makes sense. Consider the following

 Lab 1: Lab 2: GetB(); GetB(); 

if the contents of GetB() is this:

 function GetB() global B; %# do something useful B = rand; end 

What will be the value of B if Lab 1 indicated Lab 1 ? and on Lab 2 ? How are the various rand results conveyed? It will be a mess!

parfor code suitable for parfor loops can be a real pain when this code comes from what only regular for -loops has. As a rule, when you know in advance, you are going to write a computationally intensive code fragment of Matlab, write all functions and loops as parfor , starting from the very beginning. This is the only way that such errors will not cost you money when transcoding your functions.

Converting from for to parfor not generally trivial .

+8
source

GLOBAL data is difficult to use inside PARFOR because each employee is a separate MATLAB process, and global variables are not synchronized with the client (or any other process) with the employees. This would work if you initialized global data from a separate function to workers. (As Rodie points out, using the global keyword directly in the body of the PARFOR loop is not allowed - however, individual functions can do this). So, it would be legal to do this:

 parfor ii=1:matlabpool('size') myFcnWhichSetsUpGlobalData(); %# defines global OPTIONS end parfor ii=1:N result(ii) = myFcnWhichUsesGlobalData(); %# reads global OPTIONS end 

I personally would try to remove GLOBAL data from your application - this will improve their work with PARFOR and clarify the dependencies.

Another option to learn is my Worker Object Wrapper, which is designed so that you don’t have to repeatedly pass data to employees. You can use it like this:

 options = buildOptions(); w_options = WorkerObjWrapper(options); parfor ii=1:N result(ii) = myFcnNeedingOptions(ii, w_options.Value); end 
+6
source

Source: https://habr.com/ru/post/924166/


All Articles